Datetime和Pytz Timezone .weekday()问题

时间:2017-05-02 23:40:22

标签: datetime pytz

当我尝试为订单创建特定createdAt日期时间的直方图时,我遇到了问题。问题是,即使创建了时区感知日期时间,.weekday()也会显示为同一天,即使它应该是不同的时间

我用来测试这种情况的代码如下:

import datetime
import pytz

value = {
    'createdAt': '2017-04-24T00:48:03+00:00'
}
created_at = datetime.datetime.strptime(value['createdAt'], '%Y-%m-%dT%H:%M:%S+00:00')

timezone = pytz.timezone('America/Los_Angeles')

created_at_naive = created_at
created_at_aware = timezone.localize(created_at_naive)

print(created_at_naive) # 2017-04-24 00:48:03
print(created_at_aware) # 2017-04-24 00:48:03-07:00
print(created_at_naive.weekday()) # 0 (Monday)
print(created_at_aware.weekday()) # 0 (should be Sunday)

1 个答案:

答案 0 :(得分:1)

问题是您需要将日期时间实际更改为新时区:

>>> timezone('UTC').localize(created_at)
datetime.datetime(2017, 4, 24, 0, 48, 3, tzinfo=<UTC>)

>>>timezone('UTC').localize(created_at).astimezone(timezone('America/Los_Angeles'))
datetime.datetime(2017, 4, 23, 17, 48, 3, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)