Find if 24 hrs have passed between datetimes - Python
我有以下方法:
1 2 3 4 5 6 7 8 9 10 11 12 | # last_updated is a datetime() object, representing the last time this program ran def time_diff(last_updated): day_period = last_updated.replace(day=last_updated.day+1, hour=1, minute=0, second=0, microsecond=0) delta_time = day_period - last_updated hours = delta_time.seconds // 3600 # make sure a period of 24hrs have passed before shuffling if hours >= 24: print"hello" else: print"do nothing" |
我想知道,如果从
如果
1 2 3 4 | from datetime import datetime, timedelta if (datetime.utcnow() - last_updated) > timedelta(1): # more than 24 hours passed |
如果
1 2 3 4 5 6 7 | import time DAY = 86400 now = time.time() then = time.mktime(last_updated.timetuple()) if (now - then) > DAY: # more than 24 hours passed |
如果
如果c
注意:写
为了便于移植,您可以安装TZ数据库。它由python中的
1 2 3 4 5 6 7 8 | from datetime import datetime, timedelta from tzlocal import get_localzone # $ pip install tzlocal tz = get_localzone() # local timezone then = tz.normalize(tz.localize(last_updated)) # make it timezone-aware now = datetime.now(tz) # timezone-aware current time in the local timezone if (now - then) > timedelta(1): # more than 24 hours passed |
即使过去UTC偏移量不同,它也能工作。但它不能(和
上面的代码假设
1 2 3 4 5 | from datetime import datetime, timedelta then_in_utc = last_updated.replace(tzinfo=None) - last_updated.utcoffset() if (datetime.utcnow() - then_in_utc) > timedelta(1): # more than 24 hours passed |
一般注意事项:您现在应该理解为什么人们建议使用UTC时间,并且只将本地时间用于显示。
只是为了澄清一些问题,因为我不认为我们所有人都使用了
1 | if (now - then) > DAY: |
它将彻底失败。这是因为你不能将
解决方法是将对象转换为秒。
例如:
1 2 3 4 5 6 7 | from datetime import datetime then = datetime_object now = datetime.now() if (now - then).total_seconds() > NUMBER_OF_SECONDS: # do something |
希望我能帮助那些在这方面遇到问题的人。喝彩