简体   繁体   English

Python 日期时间转换为时间戳

[英]Python datetime conversion to timestamps

I am struggling to understand why the following lines of code我很难理解为什么下面的代码行

from datetime import datetime 

t1 = datetime(2019, 3, 31, 0, 0, 0).timestamp()
t2 = datetime(2019, 4, 1, 0, 0, 0).timestamp()
dt = t2-t1
print(f"dt = {dt} seconds.")

output输出

dt = 82800.0 seconds.

instead of代替

dt = 86400.0 seconds.

The time difference between t2 and t1 is clearly 1 day = 24 hours = 1440 minutes = 86400 seconds. t2 和 t1 之间的时间差显然是 1 天 = 24 小时 = 1440 分钟 = 86400 秒。 Why does this happen?为什么会发生这种情况?

那是您所在时区的那一天,时钟向前更改一小时,因为 82,000 是 23 x 60 x 60

calling eg datetime(2019, 3, 31, 0, 0, 0).timestamp() will give you a timestamp that is localized to your machine's timezone since the datetime object is not aware of any timezone ("naive"; see the docs ).调用例如datetime(2019, 3, 31, 0, 0, 0).timestamp()会给你一个本地化到你机器时区的时间戳,因为 datetime 对象不知道任何时区(“天真”;请参阅文档)。 Apparently, you are in a timezone with a DST change on that date.显然,您所在的时区在该日期发生了 DST 更改。

If you set the timezone to UTC for example (no DST), you will get the expected result:例如,如果您将时区设置为 UTC(无 DST),您将获得预期结果:

from datetime import datetime, timezone
t1 = datetime(2019, 3, 31, 0, 0, 0, tzinfo=timezone.utc).timestamp()
t2 = datetime(2019, 4, 1, 0, 0, 0, tzinfo=timezone.utc).timestamp()
dt = t2-t1

print(f"dt = {dt} seconds.")
# dt = 86400.0 seconds.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM