How to convert UTC time to local time based on city name?

Viewed 40

I have a Pandas Dataframe that has time in UTC. I also have another column that has the timezone to which I would like to convert it to

time, timezone
2022-06-23 01:00:00, Montevideo
2022-05-10 05:00:00, Brasilia
2022-07-16 22:47:00, Casablanca

I would like to convert each of these rows into their respective local timestamp based on value in the timezone column

1 Answers

With the help of Geocoder, here is one way to do it:

import geocoder
import pandas as pd

df = pd.DataFrame(
    [
        {"utc_time": "2022-06-23 01:00:00", "city": "Montevideo"},
        {"utc_time": "2022-05-10 05:00:00", "city": "Brasilia"},
        {"utc_time": "2022-07-16 22:47:00", "city": "Casablanca"},
    ]
)

# Setup
df["utc_time"] = pd.to_datetime(df["utc_time"], format="%Y-%m-%d %H:%M:%S", utc=True)

# Find time zones
df["timezone"] = df["city"].apply(
    lambda x: geocoder.geocodefarm(x).geojson["features"][0]["properties"]["raw"][
        "LOCATION_DETAILS"
    ]["timezone_short"]
)

# Get local time
df["local_time"] = df.apply(
    lambda x: x["utc_time"].tz_convert(tz=x["timezone"]), axis=1
)
                   utc_time        city            timezone                 local_time
0 2022-06-23 01:00:00+00:00  Montevideo  America/Montevideo  2022-06-22 22:00:00-03:00
1 2022-05-10 05:00:00+00:00    Brasilia   America/Sao_Paulo  2022-05-10 02:00:00-03:00
2 2022-07-16 22:47:00+00:00  Casablanca   Africa/Casablanca  2022-07-16 23:47:00+01:00
Related