我有一个具有UTC时间的Pandas Dataframe。我还有另一列,其中包含时区,我想将其转换为
time, timezone
2022-06-23 01:00:00, Montevideo
2022-05-10 05:00:00, Brasilia
2022-07-16 22:47:00, Casablanca
我想根据时区列
中的值将这些行转换为各自的本地时间戳在Geocoder的帮助下,有一种方法可以做到这一点:
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