date and time range checking

Peter Hansen peter at engcorp.com
Thu Jun 2 20:32:53 CEST 2005


Maksim Kasimov wrote:
> 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)



More information about the Python-list mailing list