Home > Enterprise >  Cannot convert timezone for a timestamp in pandas
Cannot convert timezone for a timestamp in pandas

Time:07-21

i am trying to convert a timestamp's timezone to UTC, using the following code

s = pd.to_datetime(pd.Series(['2018-10-28 01:30:00',
                          '2018-10-28 02:00:00',
                          '2018-10-28 02:30:00',
                          '2018-10-28 02:00:00',
                          '2018-10-28 02:30:00',
                          '2018-10-28 03:00:00',
                          '2018-10-28 03:30:00']))


df = pd.DataFrame(s)

df = df.tz_localize(pytz.timezone('US/Eastern')).tz_convert(pytz.timezone('UTC'))

I am getting this error

TypeError: index is not a valid DatetimeIndex or PeriodIndex

CodePudding user response:

For processing Series select column 0 and use .dt accessor:

#if input is DataFrame with column 0
df = pd.DataFrame(s)
s = df[0].dt.tz_localize(pytz.timezone('US/Eastern')).dt.tz_convert(pytz.timezone('UTC'))
print (s)
0   2018-10-28 05:30:00 00:00
1   2018-10-28 06:00:00 00:00
2   2018-10-28 06:30:00 00:00
3   2018-10-28 06:00:00 00:00
4   2018-10-28 06:30:00 00:00
5   2018-10-28 07:00:00 00:00
6   2018-10-28 07:30:00 00:00
Name: 0, dtype: datetime64[ns, UTC]

#if input is Series
s = s.dt.tz_localize(pytz.timezone('US/Eastern')).dt.tz_convert(pytz.timezone('UTC'))
print (s)
0   2018-10-28 05:30:00 00:00
1   2018-10-28 06:00:00 00:00
2   2018-10-28 06:30:00 00:00
3   2018-10-28 06:00:00 00:00
4   2018-10-28 06:30:00 00:00
5   2018-10-28 07:00:00 00:00
6   2018-10-28 07:30:00 00:00
dtype: datetime64[ns, UTC]
  • Related