首页 > 解决方案 > getmtime() 与 datetime.now():

问题描述

此代码每年在时钟转换的晚上(欧洲中部夏令时间到欧洲中部时间)打印一次错误警告:

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)

即使在每年一小时的时钟轮班期间,如何使此代码工作?

更新

我只关心年龄,而不关心日期时间。

标签: pythonclockgmt

解决方案


通过从本地时间切换到 UTC 时间,可以轻松改进发布的片段。UTC 没有夏季(夏令时)时间变化。只需替换这两个日期时间函数now()-> utcnow()( docs ) 和fromtimestamp()-> utcfromtimestamp()( docs )。

但是,如果唯一的预期输出是以秒为单位的文件年龄,我们可以直接使用时间戳(从“纪元”开始的秒数)而无需任何转换:

import time
import os.path

...
age = time.time() - os.path.getmtime(file_name)

推荐阅读