date and time range checking

M

Maksim Kasimov

there are few of a time periods, for example:
2005-06-08 12:30 -> 2005-06-10 15:30,
2005-06-12 12:30 -> 2005-06-14 15:30

and there is some date and time value:
2005-06-11 12:30

what is the "pythonic" way to check is the date/time value in the given periods range?

something like xrange:.... print "OK"


thanks
 
P

Peter Hansen

Maksim said:
what is the "pythonic" way to check is the date/time value in the given
periods range?

Something like this, though I won't make strong claims of
"pythonicness". If you want to use the "in" keyword you'll want a
custom class and overriding of __contains__.

import time
from datetime import datetime

def make_datetime(s, fmt='%Y-%m-%d %H:%M'):
'''convert string to datetime'''
ts = time.mktime(time.strptime(s, fmt))
return datetime.fromtimestamp(ts)


def inRange(s, ranges):
dt = make_datetime(s)
for begin,end in ranges:
if begin <= dt <= end:
return True
else:
return False


ranges = [(make_datetime(b), make_datetime(e)) for (b,e) in [
('2005-06-08 12:30', '2005-06-10 15:30'),
('2005-06-12 12:30', '2005-06-14 15:30'),
]]

print inRange('2005-06-11 12:30', ranges)
 
A

Andrew Dalke

Maksim said:
there are few of a time periods, for example:
2005-06-08 12:30 -> 2005-06-10 15:30,
2005-06-12 12:30 -> 2005-06-14 15:30

and there is some date and time value:
2005-06-11 12:30


what is the "pythonic" way to check is the date/time value in the given periods range?
.... print "In range"
....
In range.... print "In range"
....
In range.... print "In range"
....
If you want to use the "in" syntax
.... def __init__(self, low, high):
.... self.low = low
.... self.high = high
.... def __contains__(self, obj):
.... return self.low < obj < self.high
....
Andrew
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top