0

I keep getting crazy with all of these time functions. I have a string being in a specific format and UTC time. I want to output the time only, but in another timezone. Thats what I have, the original one is X. I want the output to be "%M:%S" but with a different timezone. I do not want to hardcode a timedelta due to daylight saving time.

x = "2022-10-11T14:00:00Z"
tz = timezone("Europe/Berlin")
tz.localize(datetime.strptime(x, "%Y-%m-%dT%H:%M:%SZ"))

THe localize line converts to the other timezone successfully, but I dont get it to just show the time in the end.

Hemmelig
  • 803
  • 10
  • 22
  • 1
    You need to parse the Z to UTC, see e.g. https://stackoverflow.com/a/62769371/10197418, then use `astimezone` to convert from UTC to whatever tz you need. – FObersteiner Oct 11 '22 at 15:18

1 Answers1

1

parse Z to UTC, the use astimezone to convert to whatever tz you need:

option with pytz and strptime, use %z to parse Z:

from datetime import datetime
import pytz

x = "2022-10-11T14:00:00Z"
dt = datetime.strptime(x, "%Y-%m-%dT%H:%M:%S%z").astimezone(pytz.timezone("Europe/Berlin"))
print(dt)
# 2022-10-11 16:00:00+02:00

pytz is deprecated, so here's a Python 3.9+ solution using fromisoformat and zoneinfo as an alternative:

from datetime import datetime
from zoneinfo import ZoneInfo

x = "2022-10-11T14:00:00Z"
dt = datetime.fromisoformat(x.replace("Z", "+00:00")).astimezone(ZoneInfo("Europe/Berlin"))
print(dt)
# 2022-10-11 16:00:00+02:00

If you're using pandas, pd.to_datetime will automatically parse Z to UTC, so you just have to use .dt.tz_convert:

import pandas as pd

df = pd.DataFrame({'dt': ["2022-10-11T14:00:00Z"]})

df["dt"] = pd.to_datetime(df["dt"]).dt.tz_convert("Europe/Berlin")

print(df)
#                          dt
# 0 2022-10-11 16:00:00+02:00
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • The first one actually works very good. The second one gets me an error if I use that together with apply in a dataframe => 'NoneType' object has no attribute 'total_seconds', which happens in the astimezone part. I will have a look for it, thank you! – Hemmelig Oct 11 '22 at 15:56
  • Edit: My original question was, how I then can convert that into the format %H:%S :) – Hemmelig Oct 11 '22 at 16:02
  • So I guess you should add .strftime("%H:%M:%S") in the end so I can accept the answer as correct :) – Hemmelig Oct 11 '22 at 16:04
  • @DORpapst it seems you're using pandas? I've added an option for this as well. Wouldn't recommend any of the two other options then. – FObersteiner Oct 11 '22 at 16:07