熊猫datetime和datetime datetime之间的差异

时间:2020-06-29 12:23:38

标签: python pandas datetime gmt

嗨,我有一些datetime.datetime格式的日期,我用它们来过滤带有panda时间戳的panda数据帧。我只是尝试了以下方法,并获得了2小时的补偿:

from datetime import datetime
import pandas as pd
pd.to_datetime(datetime(2020, 5, 11, 0, 0, 0).timestamp()*1e9)

输出为:

->Timestamp('2020-05-10 22:00:00')

任何人都可以解释为什么这会造成2个小时的偏移吗?我在丹麦,所以它对应于GMT的偏移量。是这个原因。我当然可以增加2个小时,但想了解为什么以后要使脚本更健壮。

感谢您对Jesper的帮助

2 个答案:

答案 0 :(得分:1)

pd.to_datetime接受一个datetime对象,因此您可以这样做(熊猫假定UTC):

pd.to_datetime(datetime(2020, 5, 11))

转换为时间戳时,您会得到2个小时的偏移,因为默认情况下python的datetime不知道时区,并且会给您一个“天真”的datetime对象(文档位于此处{{3 }}。生成的时间戳将在本地时区,因此是2小时的偏移量。

您可以将tzinfo参数传递给datetime对象,指定将时间视为UTC:

from datetime import datetime
import pandas as pd
import pytz

pd.to_datetime(datetime(2020, 5, 11, 0, 0, 0, tzinfo=pytz.UTC).timestamp()*1e9)

或者,您可以使用calendar模块生成UTC时间戳:

from datetime import datetime
import pandas as pd
import calendar

timestamp = calendar.timegm(datetime(2020, 5, 11, 0, 0, 0).utctimetuple())
pd.to_datetime(timestamp*1e9)

答案 1 :(得分:0)

如果您的日期时间对象实际上代表了本地时间(即您的操作系统设置),则只需使用

from datetime import datetime
import pandas as pd

t = pd.to_datetime(datetime(2020, 5, 11).astimezone())
# e.g. I'm on CEST, so t is
# Timestamp('2020-05-11 00:00:00+0200', tz='Mitteleuropäische Sommerzeit')

请参阅:How do I get a value of datetime.today() in Python that is “timezone aware”?


请记住,pandas将把朴素的Python日期时间对象当作UTC:

from datetime import timezone

t1 = pd.to_datetime(datetime(2020, 5, 11, tzinfo=timezone.utc))
t2 = pd.to_datetime(datetime(2020, 5, 11))

t1.timestamp() == t2.timestamp()
# True

另请参阅:Python datetime and pandas give different timestamps for the same date