为什么datetime.now()和datetime.utcnow()返回不同的时间戳 [英] why datetime.now() and datetime.utcnow() return different timestamp

查看:585
本文介绍了为什么datetime.now()和datetime.utcnow()返回不同的时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用日期时间,发现很难理解timestamp()的工作原理,我(在东海岸)想将日期时间转换为时间戳,但是我发现以下区别。任何人都可以阐明这两个代码的工作方式,是否应该采取不同的行动(大约相差四个小时)?

I'm working with datetime and find it difficult to understand how timestamp() works, I (in east coast) want to transform the datetime into timestamp, but I found following difference. Can anyone shed somelight how each of the two code works, are they suppose to act differently (roughly a difference of four hours)?

import datetime
datetime.datetime.utcnow().timestamp()
#1590436949.187297
datetime.datetime.now(tz=datetime.timezone.utc).timestamp()
#1590422553.042119


推荐答案

timestamp() 方法返回自该纪元以来的POSIX时间戳/秒,始终指UTC。

The timestamp() method returns a POSIX timestamp / seconds since the epoch which always refers to UTC.

重要:如果您将朴素的datetime对象传递给 timestamp(),则Python将假定datetime对象保存 本地时间

Important: if you pass a naive datetime object to timestamp(), Python will assume that the datetime object holds local time.

这是 datetime.datetime.utcnow()的问题。尽管名称 utcnow()可能表示相反,但它为您提供了一个简单的日期时间对象,即它不知道它在UTC中。因此,如果调用 timestamp()方法,Python 假定传递给该函数的datetime对象是本地时间,而不是本地时间。您将获得 time.time()

That is the issue with datetime.datetime.utcnow(). Although the name utcnow() might suggest otherwise, it gives you a naive datetime object, i.e. it does not "know" it's in UTC. Therefore, if you call the timestamp() method, Python assumes that the datetime object passed to the function is in local time and it is not what you would get from time.time().

另一方面,在 datetime.datetime.now(tz = datetime.timezone。 utc).timestamp(),则将时区感知日期时间对象传递给 timestamp()。在给您 time.time()的意义上,这是正确的。

On the other hand, in datetime.datetime.now(tz=datetime.timezone.utc).timestamp(), you pass a timezone-aware datetime object to timestamp(). That is correct in the sense that it gives you time.time().

插图:

import datetime
import time
import dateutil
localtzname = time.tzname[time.daylight]

# naive:
dt_now = datetime.datetime.now()
# timezone-aware:
dt_now_loc = datetime.datetime.now(dateutil.tz.gettz(localtzname))
dt_now_utc = datetime.datetime.now(tz=datetime.timezone.utc)
# reference:
ts = time.time()

print(dt_now.timestamp())
# 1590424623.226529

print(dt_now_loc.timestamp())
# 1590424623.226529

print(dt_now_utc.timestamp())
# 1590424623.226529

print(ts)
# 1590424623.2265291

如您所见,即使 dt_now 天真,Python也会返回与从本地化的 dt_now_loc 或从 time.time()开始。

As you can see, even though dt_now is naive, Python returns the same timestamp as you get from the localized dt_now_loc or from time.time().

总之, d atetime.datetime.utcnow()。timestamp()可能会引起误解,我建议您避免使用它。

In summary, datetime.datetime.utcnow().timestamp() can be pretty misleading and I would recommend avoiding it.

这篇关于为什么datetime.now()和datetime.utcnow()返回不同的时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆