If you have time series data that originates from a certain time zone, but does not explicitly contain that information,
- set the time zone by replaceing the tzinfo attribute with the appropriate time zone object.
Once the time zone is defined for a datetime object (it is aware),
- you can convert to another time zone using astimezone.
EX:
from datetime import datetime
from zoneinfo import ZoneInfo
s = "2021-06-18 14:02:00"
# a date/time as string; we might know that this originates from a
# certain time zone, let's take "Europe/Berlin" for example
origin_tz = ZoneInfo("Europe/Berlin")
# parse the string to datetime and set the time zone
dt = datetime.fromisoformat(s).replace(tzinfo=origin_tz)
print(dt)
# 2021-06-18 14:02:00+02:00
print(repr(dt))
# datetime.datetime(2021, 6, 18, 14, 2, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))
# we can easily get e.g. corresponding UTC time:
print(dt.astimezone(ZoneInfo('UTC')))
# 2021-06-18 12:02:00+00:00
Note for legacy code that still uses pytz
: you must use localize
to set a time zone, otherwise you get the weird timezone issue with pytz.