为什么pytz.localize和datetime.replace返回不同的结果?

2024-09-27 02:17:43 发布

您现在位置:Python中文网/ 问答频道 /正文

正如documentation of pytz所说:

def localize(self, dt, is_dst=False):
    '''Convert naive time to local time'''
    if dt.tzinfo is not None:
        raise ValueError('Not naive datetime (tzinfo is already set)')
    return dt.replace(tzinfo=self)

如最后一行所示,localize和dt.replace是相同的。因为上面的算法,如果我们去掉if部分,就是return dt.replace(tzinfo=self),它只使用datetime.replace

但我们知道输出是不同的:

time = datetime.now()
tehran_tz = pytz.timezone('Asia/Tehran')
print(tehran_tz.localize(time))
print(time.replace(tzinfo=tehran_tz))

输出:

2021-02-22 21:15:29.781400+03:30 2021-02-22 21:15:29.781400+03:26

这不是关于哪一个是正确的。但是为什么它们是不同的,而它们的代码是相同的呢


Tags: selfdatetimereturniftimeisdtreplace

热门问题