gpt4 book ai didi

Pandas timestamp 和 python datetime 对时区的解释不同

转载 作者:行者123 更新时间:2023-12-04 01:57:08 24 4
gpt4 key购买 nike

我不明白为什么 ab 不一样:

import pandas as pd
from datetime import datetime
import pytz

here = pytz.timezone('Europe/Amsterdam')

a = pd.Timestamp('2018-4-9', tz=here).to_pydatetime()
# datetime.datetime(2018, 4, 9, 0, 0, tzinfo=<DstTzInfo'Europe/Amsterdam' CEST+2:00:00 DST>)
b = datetime(2018, 4, 9, 0, tzinfo=here)
# datetime.datetime(2018, 4, 9, 0, 0, tzinfo=<DstTzInfo 'Europe/Amsterdam' LMT+0:20:00 STD>)

print(b-a)
# returns 01:40:00

最佳答案

从这里stackoverflow post我了解到 tzinfo 对于某些时区效果不佳,这可能是导致错误结果的原因。 pytz doc :

Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones.

解决方案是使用localizeastimezone:

import pandas as pd
from datetime import datetime
import pytz

here = pytz.timezone('Europe/Amsterdam')

a = pd.Timestamp('2018-4-9', tz=here).to_pydatetime()
# datetime.datetime(2018, 4, 9, 0, 0, tzinfo=<DstTzInfo'Europe/Amsterdam' CEST+2:00:00 DST>)
b = here.localize(datetime(2018, 4, 9))
# datetime.datetime(2018, 4, 9, 0, 0, tzinfo=<DstTzInfo 'Europe/Amsterdam' CEST+2:00:00 DST>)

print(b-a)
# returns 00:00:00

关于Pandas timestamp 和 python datetime 对时区的解释不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49777178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com