'Converting a datetime to local time based on timezone in Python3

I have a question related to dates and time in Python.

Problem:

date = datetime.datetime.strptime(str(row[1]), "%Y-%m-%d %H:%M:%S")
localtime = date.astimezone(pytz.timezone("Europe/Brussels"))
formattedDate = localtime.strftime("%Y-%m%-%d")
  1. In the code above, str(row[1]) gives back a UTC datetime coming from a mysql database: 2022-02-28 23:00:00
  2. I parse this as a datetime and change the timezone to Europe/Brussels.
  3. I then format it back to a string.

Expected result:

I'd like to return the date in local time. Europe/Brussels adds one hour so I would expect that strftime returns 2022-03-01, but it keeps returning 2022-02-28.

Can somebody help?



Solution 1:[1]

Ah, I see!

I ended up doing this, basically the same as you mentioned:

from_zone = tz.gettz('UTC')
to_zone = tz.gettz('Europe/Brussels')
utcdate = datetime.datetime.strptime(str(row[1]), "%Y-%m-%d %H:%M:%S")
utcdate = utcdate.replace(tzinfo=from_zone)
localdate = utcdate.astimezone(to_zone)
formattedLocalDate = localdate.strftime("%Y%m%d");

The naïve date gets UTC aware by the utcdate.replace(tzinfo=from_zone).

Thanks for helping!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim De Paepe