简体   繁体   中英

Check if a timestamp string is within a time range

I need check if a timestamp string is into a time range:

tt = '26-12-2012 18:32:51'
t1 = datetime.timedelta(0, 28800) #08:00 hrs
t2 = datetime.timedelta(0, 68400) #19:00 hrs

To compare do I need convert the timestamp into a timedelta?, how can I do that, to compare like:

if tt >= t1 and tt <= t2:

Thanks..

First, construct a datetime object with datetime.strptime :

>>> t = datetime.datetime.strptime('26-12-2012 18:32:51', '%d-%m-%Y %H:%M:%S')
>>> t
datetime.datetime(2012, 12, 26, 18, 32, 51)

Now, construct a second datetime object which only represents the date portion:

>>> t2 = t.replace(hour=0, minute=0, second=0)

From that you can get a datetime.timedelta suitable for comparing with your other timedelta s:

>>> t - t2
datetime.timedelta(0, 66771)
>>> dt = t - t2
>>> dt1 = datetime.timedelta(0, 28800) #08:00 hrs
>>> dt2 = datetime.timedelta(0, 68400) #08:00 hrs
>>> dt > dt1
True
>>> dt2 > dt > dt1
True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM