0

我正在尝试计算“现在”和新年前夜之间的时差……例如。当我将时区信息设置为“欧洲/罗马”时,计算中会出现 10 分钟的错误。没有时区信息,错误为 1 小时。

我究竟做错了什么???

这是一个示例代码:

from datetime import datetime
import pytz

now   = datetime.now()
nowtz = datetime.now(tz=pytz.timezone("Europe/Rome"))

fut   = datetime(2022,12,31,23,59,59)
futtz = datetime(2022,12,31,23,59,59,tzinfo=pytz.timezone("Europe/Rome"))

delta = fut - now
deltatz = futtz - nowtz

print("Without timezone:")
print("Now: " + now.strftime("%Y/%m/%d %H:%M:%S"))
print("Tar: " + fut.strftime("%Y/%m/%d %H:%M:%S"))
print("Dif: " + str(delta))
print("")
print("With timezone:")
print("Now: " + nowtz.strftime("%Y/%m/%d %H:%M:%S"))
print("Tar: " + futtz.strftime("%Y/%m/%d %H:%M:%S"))
print("Dif: " + str(deltatz))

和一个输出:

Without timezone:
Now: 2021/10/05 14:12:09
Tar: 2022/12/31 23:59:59
Dif: 452 days, 9:47:49.933575

With timezone:
Now: 2021/10/05 14:12:09
Tar: 2022/12/31 23:59:59
Dif: 452 days, 10:57:49.908281

在python中计算时间差的正确方法是什么?

对于我使用的参考值:https ://www.timeanddate.com/counters/newyear.html?p0=215

4

1 回答 1

0

对于其他偶然发现此问题的人,这是一个解决方案:

from datetime import datetime
import pytz

tzone = pytz.timezone("Europe/Rome")

now   = datetime.now().astimezone()
nowtz = datetime.now(tz=tzone)

fut   = datetime(2021,12,31,23,59,59).astimezone()
futtz = tzone.localize(datetime(2021,12,31,23,59,59), is_dst=None)

delta = fut - now
deltatz = futtz - nowtz

print("Without timezone:")
print("Now: " + now.strftime("%Y/%m/%d %H:%M:%S"))
print("Tar: " + fut.strftime("%Y/%m/%d %H:%M:%S"))
print("Dif: " + str(delta))
print("")
print("With timezone:")
print("Now: " + nowtz.strftime("%Y/%m/%d %H:%M:%S"))
print("Tar: " + futtz.strftime("%Y/%m/%d %H:%M:%S"))
print("Dif: " + str(deltatz))

带输出:

Without timezone:
Now: 2021/10/05 14:22:27
Tar: 2021/12/31 23:59:59
Dif: 87 days, 10:37:31.187800

With timezone:
Now: 2021/10/05 14:22:27
Tar: 2021/12/31 23:59:59
Dif: 87 days, 10:37:31.187783
于 2021-10-05T12:24:39.740 回答