Home > other >  Python: Read UTC string, output other timezone with format
Python: Read UTC string, output other timezone with format

Time:10-12

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.

CodePudding user response:

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
  • Related