要比较文件中的时间,您应该将其转换为 UTC 时间(POSIX 时间戳)或可识别的日期时间对象(本地时间 + UTC 偏移量)。
start_time, end_time = get_times('hour', -3, -1.2)
if start_time <= utc_time < end_time:
# utc_time is in between
您应该不使用start_time <= naive_local_time < end_time。 Convert input time to UTC or create an aware datetime objects instead.
如果您的输入文件中的当地时间是连续的,那么您可以在必要时使用该事实来消除时间戳的歧义,请参阅Parsing of Ordered Timestamps in Local Time (to UTC) While Observing Daylight Saving Time。
更多使用time.mktime()、pytz、感知日期时间对象的解释和解决方案在:Find if 24 hrs have passed between datetimes - Python。
为什么你不应该使用datetime.now()
datetime.now() 返回本地时间,因为简单的日期时间对象可能不明确,例如在 DST 转换期间:
>>> from datetime import datetime
>>> import pytz
>>> tz = pytz.timezone('America/New_York')
>>> tz.localize(datetime(2015,11,1,1,30), is_dst=None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/pytz/tzinfo.py", line 349, in localize
raise AmbiguousTimeError(dt)
pytz.exceptions.AmbiguousTimeError: 2015-11-01 01:30:00
>>> tz.localize(datetime(2015,11,1,1,30), is_dst=True).astimezone(pytz.utc)
datetime.datetime(2015, 11, 1, 5, 30, tzinfo=<UTC>)
>>> tz.localize(datetime(2015,11,1,1,30), is_dst=False).astimezone(pytz.utc)
datetime.datetime(2015, 11, 1, 6, 30, tzinfo=<UTC>)
注意:如果您删除 UTC 偏移量,则相同的本地时间可能对应不同的 UTC 时间。 datetime.utcnow() 是明确的(除了可能在闰秒期间,例如2015-06-30T23:59:60Z)。
如何实现get_times('hour', -3.0, -1.2)
使用 UTC 时间或感知日期时间对象:
#!/usr/bin/env python
from datetime import datetime, timedelta
def get_times(unit, relative_start, relative_end):
relative_start, relative_end = [timedelta(**{unit+'s': v})
for v in [relative_start, relative_end]]
now = datetime.utcnow() # or datetime.now(timezone.utc).astimezone()
return now + relative_start, now + relative_end