I've got some date and time data as a string that is formatted like this, in UTC:
,utc_date_and_time, api_calls
0,2022-10-20 00:00:00,12
1,2022-10-20 00:05:00,14
2,2022-10-20 00:10:00,17
Is there a way to create another column here that always represents that time, but so it is for London/Europe?
,utc_date_and_time, api_calls, london_date_and_time
0,2022-10-20 00:00:00,12,2022-10-20 01:00:00
1,2022-10-20 00:05:00,14,2022-10-20 01:05:00
2,2022-10-20 00:10:00,17,2022-10-20 01:10:00
I want to write some code that, for any time of the year, will display the time in London - but I'm worried that when the timezone changes in London/UK that my code will break.
CodePudding user response:
You should use utc timezone
from datetime import datetime, timezone
datetime.now(timezone.utc).isoformat()
Outputs:
2022-10-25T15:27:08.874057 00:00
CodePudding user response:
with pandas
, you'd convert to datetime, specify UTC and then call tz_convert:
df
Out[9]:
utc_date_and_time api_calls
0 2022-10-20 00:00:00 12
1 2022-10-20 00:05:00 14
2 2022-10-20 00:10:00 17
df["utc_date_and_time"] = pd.to_datetime(df["utc_date_and_time"], utc=True)
df["london_date_and_time"] = df["utc_date_and_time"].dt.tz_convert("Europe/London")
df
Out[12]:
utc_date_and_time api_calls london_date_and_time
0 2022-10-20 00:00:00 00:00 12 2022-10-20 01:00:00 01:00
1 2022-10-20 00:05:00 00:00 14 2022-10-20 01:05:00 01:00
2 2022-10-20 00:10:00 00:00 17 2022-10-20 01:10:00 01:00
in vanilla Python >= 3.9, you'd let zoneinfo handle the conversion;
from datetime import datetime
from zoneinfo import ZoneInfo
t = "2022-10-20 00:00:00"
# to datetime, set UTC
dt = datetime.fromisoformat(t).replace(tzinfo=ZoneInfo("UTC"))
# to london time
dt_london = dt.astimezone(ZoneInfo("Europe/London"))
print(dt_london)
2022-10-20 01:00:00 01:00