python - 从使用 utcfromtimestamp 实例化的日期时间检索时间戳

标签 python python-3.x timestamp python-3.6

在 Python 脚本中,我用时间戳值实例化了一个 datetime。 我无法检索到原始时间戳。

例子:

origin_timestamp = 1554840000
utc_datetime = datetime.datetime.utcfromtimestamp(origin_timestamp)
calculated_timestamp = utc_datetime.timestamp()
print("===== calculated_timestamp =====")
print(calculated_timestamp)

print("===== EQUAL TIMESTAMP =====")
print(origin_timestamp == calculated_timestamp)

在 CLI 中显示以下行:

===== calculated_timestamp =====
1554829200.0
===== EQUAL TIMESTAMP =====
False

我在 documentation 中没有找到任何内容获取时间戳。您知道检索我的原始时间戳的方法吗?

最佳答案

问题是天真的 datetime 实例被假设为代表本地时间,这会影响 timestamp() 方法的作用。您可以通过调用以下命令创建时区感知的 utc datetime 实例来解决此问题:

utc_datetime.replace(tzinfo=datetime.timezone.utc)

这是一个完整的例子:

import datetime


origin_timestamp = 1554840000

print("===== origin_timestamp =====")
print(origin_timestamp)

utc_datetime = datetime.datetime.utcfromtimestamp(origin_timestamp)
print("===== utc_datetime =====")
print(utc_datetime)

# Add a timezone to utc_datetime
utc_datetime2 = utc_datetime.replace(tzinfo=datetime.timezone.utc)
print("===== utc_datetime2 =====")
print(utc_datetime2)

# Use it.
calculated_timestamp = utc_datetime2.timestamp()
print("===== calculated_timestamp =====")
print(calculated_timestamp)

print("===== difference =====")
print(calculated_timestamp - origin_timestamp)

print("===== EQUAL TIMESTAMP =====")
print(origin_timestamp == calculated_timestamp)

输出:

===== origin_timestamp =====
1554840000
===== utc_datetime =====
2019-04-09 20:00:00
===== utc_datetime2 =====
2019-04-09 20:00:00+00:00
===== calculated_timestamp =====
1554840000.0
===== difference =====
0.0
===== EQUAL TIMESTAMP =====
True

仅供引用:帮助我弄清楚发生了什么的主要线索是打印两个时间戳之间的差异,即 25200 秒 — 正好是 7.0 小时 — 这看起来有点像与 UTC 的时区偏移(无论如何在美国这里)。 datatime.timestamp() 的文档确认这是实例方法所做的。

我的意思是:

>>> m = 25200 / 60  # difference in minutes
>>> m
420.0
>>> h = m / 60  # in hours
>>> h
7.0

关于python - 从使用 utcfromtimestamp 实例化的日期时间检索时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55602561/

相关文章:

python - 将字节写入波形文件?

php - 负 float 日期

python - psycopg2 的服务器连接状态值是什么意思?

python - 为什么 groupby.diff 这么慢?

python - Windows 上的 "Unable to find vcvarsall.bat"错误

python - IGraph python 从顶点获取邻居顶点

python - 如何使用 pdfrw 库编辑可编辑的 pdf?

python - 使用 urllib 而不是 http.client 登录网站

PHP 时间戳非法值

postgresql - 在 COMMENT ON TABLE 中放置时间戳