python - pandas 日期时间转换不一致

标签 python pandas datetime timezone

可重现的示例:

import pandas as pd
now = pd.Timestamp('2018-04-09 09:10')
start_of_today = pd.datetime(now.year, now.month, now.day, 0)
print(pd.to_datetime(start_of_today.timestamp(), unit='s'))

最后一行将返回 2018-04-08 22:00:00 而不是 2018-04-09 00:00,为什么会发生这种情况?

最佳答案

根据datetime.timestamp documentation :

For aware datetime instances, the return value is computed as:

(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()

因此,您需要将 pd.datetime 对象与 UTC 时区对齐:

from datetime import timezone
import pandas as pd

now = pd.Timestamp('2018-04-09 09:10')
start_of_today = pd.datetime(now.year, now.month, now.day, 0, 0, 0, 0, timezone.utc)
print(pd.to_datetime(start_of_today.timestamp(), unit='s'))

关于python - pandas 日期时间转换不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49770856/

相关文章:

python - 在 Python 中使用 Timer 对象的错误输出

java - 如何在android中查找当月的星期六和星期日?

python - 为什么我的 Fortran 代码用 f2py 包装使用了这么多内存?

python - Sklearn 流水线的核外学习

python - 在 Pyglet 中设置单个像素

python-2.7 - 格式化 Pandas 数据框中数字的千位分隔符

python - 使用按列值拆分的 2 个系列创建线图

python - 使用 pandas 总结分类问卷数据

sql-server - 将 SQL Server 数据库而非整个服务器上的日期格式更改为 dd/mm/yyyy

c# - 检查日期时间字符串是否包含时间