1

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.

  • 1
    [This blog entry](https://blog.ganssle.io/articles/2018/03/pytz-fastest-footgun.html) might give some insight. By the way, Python 3.9 has [zoneinfo](https://docs.python.org/3/library/zoneinfo.html), which could help prevent some "localize-vs-replace" head aches. – FObersteiner Feb 22 '21 at 18:32

0 Answers0