I want to convert a variable time UTC to Local time according to Local_timezone
variable.
I have a dataframe time_df with variable TIMEZONE
and a second dataframe data_df
with variable time_utc
.
I want to create a local_time variable in my dataframe.
TIMEZONE
is a string and time_utc
is a datetime.
I do it like this:
local_timezone = time_df['TIMEZONE']
data_df.loc[data_df['time_utc'].tz_convert(local_timezone), 'local_time']
I have this error:
TypeError: index is not a valid DatetimeIndex or PeriodIndex
CodePudding user response:
Let say you merge data_df
with time_df
already. It means that your data_df
will have time_utc
, TIMEZONE
, and etc.
e.g.
local_timezone = time_df['TIMEZONE']
local_timezone = local_timezone.to_frame('TIMEZONE')
data_df = pd.concat([data_df , local_timezone], axis=1)
To convert the time zone of time_utc
to local time, use apply()
to apply a time zone to each value.
def set_timezone(row):
return row['time_utc'].tz_convert(row['TIMEZONE'])
data_df['local_time'] = data_df.apply(lambda x: set_timezone(x), axis = 1)
OUTPUT
Before:
>>> data_df
time_utc TIMEZONE
0 2021-12-03 01:33:00 00:00 Europe/Paris
1 2021-12-03 03:50:00 00:00 Europe/Paris
After:
>>> data_df['local_time'] = data_df.apply(lambda x: set_timezone(x), axis = 1)
>>> data_df
time_utc TIMEZONE local_time
0 2021-12-03 01:33:00 00:00 Europe/Paris 2021-12-03 02:33:00 01:00
1 2021-12-03 03:50:00 00:00 Europe/Paris 2021-12-03 04:50:00 01:00