简体   繁体   中英

Converting a naive datetime column to a new timezone Pandas Dataframe

I have the following dataframe, named 'ORDdataM', with a DateTimeIndex column 'date', and a price point column 'ORDprice'. The date column has no timezone associated with it (and is naive) but is actually in 'Australia/ACT'. I want to convert it into 'America/New_York' time.

                    ORDprice
date    
2021-02-23 18:09:00 24.01
2021-02-23 18:14:00 23.91
2021-02-23 18:19:00 23.98
2021-02-23 18:24:00 24.00
2021-02-23 18:29:00 24.04
... ...
2021-02-25 23:44:00 23.92
2021-02-25 23:49:00 23.88
2021-02-25 23:54:00 23.92
2021-02-25 23:59:00 23.91
2021-02-26 00:09:00 23.82

The line below is one that I have played around with quite a bit, but I cannot figure out what is erroneous. The only error message is: KeyError: 'date'

ORDdataM['date'] = ORDdataM['date'].dt.tz_localize('Australia/ACT').dt.tz_convert('America/New_York')

I have also tried

ORDdataM.date = ORDdataM.date.dt.tz_localize('Australia/ACT').dt.tz_convert('America/New_York')

What is the issue here?

Your date is index not a column, try:

df.index = df.index.tz_localize('Australia/ACT').tz_convert('America/New_York')

df
#                           ORDprice
#date                               
#2021-02-23 02:09:00-05:00     24.01
#2021-02-23 02:14:00-05:00     23.91
#2021-02-23 02:19:00-05:00     23.98
#2021-02-23 02:24:00-05:00     24.00
#2021-02-23 02:29:00-05:00     24.04
#2021-02-25 07:44:00-05:00     23.92
#2021-02-25 07:49:00-05:00     23.88
#2021-02-25 07:54:00-05:00     23.92
#2021-02-25 07:59:00-05:00     23.91
#2021-02-25 08:09:00-05:00     23.82

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM