4

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)?

Vojtooo
  • 103
  • 2
  • 6
  • 1
    please leave examples of expected vs actual output – notacorn Jun 18 '21 at 05:19
  • 1
    related: https://stackoverflow.com/a/64097432/10197418 - note that a string that you can parse with `"%Y-%m-%d %H:%M:%S.%f"` has no time zone / UTC offset information. The resulting datetime object will be naive (unaware of a tz). Naive datetime objects are treated as *local time* by Python, not UTC. – FObersteiner Jun 18 '21 at 05:48

1 Answers1

7

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.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72