此代码每年在时钟的夜晚(欧洲中部夏令时至中欧时间)打印一次错误警告:
import os
import datetime
now = datetime.datetime.now()
age = now - datetime.datetime.fromtimestamp(os.path.getmtime(file_name))
if (age.seconds + age.days * 24 * 3600) < -180:
print('WARN: file has timestap from future?: %s' % age)
即使在每年一小时的轮班期间如何使此代码正常工作?
您的日期时间对象都是'naive',这意味着它们不了解DST。本地化日期时间对象应该可以为您提供帮助;像
from datetime import datetime
import tzlocal
now_aware = tzlocal.get_localzone().localize(datetime.now())
file_mtime = datetime.fromtimestamp(os.path.getmtime(file))
file_mtime = now_aware.tzinfo.localize(file_mtime)
age = now_aware - file_mtime
使用时区可能会使您发疯……但是那里有一些很好的资源,例如this medium post。