Home > other >  Converting a datetime to local time based on timezone in Python3
Converting a datetime to local time based on timezone in Python3

Time:03-03

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?

CodePudding user response:

date is a naïve date, without timezone, because no timezone information was in the string you parsed. Using astimezone on that simply attaches timezone information to it, turning a naïve date into an aware one. It obviously can't convert any times, because it doesn't know what to convert from.

This also already contains the answer: make the date aware that it's in UTC first before trying to convert it to a different timezone:

date = datetime.datetime.strptime(...).astimezone(datetime.timezone.utc)

CodePudding user response:

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!

  • Related