getmtime()vs datetime.now():

gue*_*tli 8 python clock gmt

该代码每年在时钟的晚上(欧洲中部夏令时至中欧时间)每年一次输出错误警告:

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)
Run Code Online (Sandbox Code Playgroud)

即使在每年一小时的轮班中,如何使此代码正常工作?

更新资料

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

VPf*_*PfB 6

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

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

import time
import os.path

...
age = time.time() - os.path.getmtime(file_name)
Run Code Online (Sandbox Code Playgroud)

  • 首先使用UTC是普遍正确的方法。 (3认同)