As documentation of pytz says:
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)
So as the last line shows, localize and dt.replace are the same. Because the algorithm above, if we remove the if
part, is return dt.replace(tzinfo=self)
which just use datetime.replace
.
But we know that the output are different:
time = datetime.now()
tehran_tz = pytz.timezone('Asia/Tehran')
print(tehran_tz.localize(time))
print(time.replace(tzinfo=tehran_tz))
Output:
2021-02-22 21:15:29.781400+03:30
2021-02-22 21:15:29.781400+03:26
It's not about which one is correct which is discussed here. But why they are different while their code are the same.