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
这不是关于哪一个是正确的。但是为什么它们是不同的,而它们的代码是相同的呢
目前没有回答
相关问题 更多 >
编程相关推荐