将 datetime 转换为 Unix 时间戳并将其转换回 python

2022-01-13 00:00:00 python datetime timestamp

问题描述

我有 dt = datetime(2013,9,1,11),我想获取这个 datetime 对象的 Unix 时间戳.

I have dt = datetime(2013,9,1,11), and I would like to get a Unix timestamp of this datetime object.

当我执行 (dt - datetime(1970,1,1)).total_seconds() 时,我得到了时间戳 1378033200.

When I do (dt - datetime(1970,1,1)).total_seconds() I got the timestamp 1378033200.

当使用 datetime.fromtimestamp 将其转换回来时,我得到了 datetime.datetime(2013, 9, 1, 6, 0).

When converting it back using datetime.fromtimestamp I got datetime.datetime(2013, 9, 1, 6, 0).

时间不匹配.我在这里错过了什么?

The hour doesn't match. What did I miss here?


解决方案

你在这里错过的是时区.

What you missed here is timezones.

假设您已经离开 UTC 五个小时,所以 2013-09-01T11:00:00 local 和 2013-09-01T06:00:00Z 是同一时间.

Presumably you've five hours off UTC, so 2013-09-01T11:00:00 local and 2013-09-01T06:00:00Z are the same time.

您需要阅读 datetime 文档的顶部,其中解释时区和天真"和有意识"的对象.

You need to read the top of the datetime docs, which explain about timezones and "naive" and "aware" objects.

如果您最初的原始日期时间是 UTC,则恢复它的方法是使用 utcfromtimestamp 而不是 fromtimestamp.

If your original naive datetime was UTC, the way to recover it is to use utcfromtimestamp instead of fromtimestamp.

另一方面,如果您最初的原始日期时间是本地的,那么您一开始就不应该从中减去 UTC 时间戳;请改用 datetime.fromtimestamp(0).

On the other hand, if your original naive datetime was local, you shouldn't have subtracted a UTC timestamp from it in the first place; use datetime.fromtimestamp(0) instead.

或者,如果您有一个感知日期时间对象,您需要在双方都使用本地(感知)纪元,或者显式转换为 UTC.

Or, if you had an aware datetime object, you need to either use a local (aware) epoch on both sides, or explicitly convert to and from UTC.

如果您拥有或可以升级到 Python 3.3 或更高版本,则只需使用 timestamp 方法,而不是试图自己弄清楚如何去做.即使你不这样做,你也可以考虑借用它的源代码.

If you have, or can upgrade to, Python 3.3 or later, you can avoid all of these problems by just using the timestamp method instead of trying to figure out how to do it yourself. And even if you don't, you may want to consider borrowing its source code.

(如果您可以等待 Python 3.4,那么看起来 PEP 341 可能会使其进入最终版本,这意味着 JF Sebastian 和我在评论中讨论的所有内容都应该仅使用 stdlib 即可实现,并且在 Unix 和 Windows 上以相同的方式工作.)

(And if you can wait for Python 3.4, it looks like PEP 341 is likely to make it into the final release, which means all of the stuff J.F. Sebastian and I were talking about in the comments should be doable with just the stdlib, and working the same way on both Unix and Windows.)

相关文章