0

This question was flagged as already answered, but it has not been previously answered. The two linked answers do not address the question I have here. One provides an example when the timezone is a given and constant for all records in the dataframe and the timezone is specified using standard timezone format, like America/Los_Angeles, but that doesn't apply in my case where my time zone is listed as a difference in hours, and that difference is not constant across all records.

I have a pandas data frame that containing two fields: hour listed in UTC, and the local time zone listed as -5:00 (for example). I want to modify the data frame so that it creates a new field containing the local time.

data = [['7:00', '-5:00'], ['6:30', '-5:00'], ['8:00', '-6:00']]

df = pd.DataFrame(data, columns = ['Hour', 'TimeZone'])

I have tried converting the TimeZone into an integer and then usig

df['LocalTime'] = pd.to_datetime(df['Hour'])-datetime.timedelta(hours = df['TimeZone')

but that didn't work for me

I also tried to convert the timezone into an integer (because in this case, I know that they will only exist as whole numbers), and then I get an error indicating I can't use a series value for the hours input variable.

Can someone help me figure out what I need to do to accomplish this?

Thanks, Brad

Brad Davis
  • 1,063
  • 3
  • 18
  • 38

1 Answers1

1

Try converting df.Hour + df.TimeZone with the utc=True option:

df['LocalTime'] = pd.to_datetime(df.Hour + df.TimeZone, utc=True)

#    Hour TimeZone                 LocalTime
# 0  7:00    -5:00 2021-09-07 12:00:00+00:00
# 1  6:30    -5:00 2021-09-07 11:30:00+00:00
# 2  8:00    -6:00 2021-09-07 14:00:00+00:00
tdy
  • 36,675
  • 19
  • 86
  • 83