大熊猫日期时间转换不一致

时间:2018-04-11 09:02:19

标签: 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,为什么会这样?

2 个答案:

答案 0 :(得分:2)

根据datetime.timestamp documentation

  

对于有意识的日期时间实例,返回值计算如下:

     

(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'))

答案 1 :(得分:1)

这是因为datetime.timestamp

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

时区是utc

你可以看到

In [65]: start_of_today.timestamp()
Out[65]: 1523203200.0

In [66]: pd.Timestamp('2018-04-09 00:00').timestamp()
Out[66]: 1523232000.0

他们的时间戳不同。