Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify timezone when loading using datetime.strptime

I have time data that I am converting into timestamp using

datetime.datetime.strptime(x,"%Y-%m-%d %H:%M:%S.%f")

The issue is that this implicitly loads the time as UTC and when I try to change it to my local timezone, it adds/subtracts time (converts it).

How can I load a string as timestamp and set it to a local timezone (which has summer time)?

like image 277
Vojtooo Avatar asked Mar 11 '26 02:03

Vojtooo


1 Answers

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.

like image 151
FObersteiner Avatar answered Mar 13 '26 14:03

FObersteiner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!