简体   繁体   中英

How to make datetimes timezone aware and convert timezones

I have 3 dataframes with multiple columns, with 2 of them having a datetime that is is UTC, and the other one being 'Europe/Amsterdam'. However, they are still unaware.

How do I make these datasets timezone aware, and convert the 'Europe/Amsterdam' to UTC?

The datetimes are in the index of each dataset.

If you're using pandas Dataframes and Python 3, you can do it like this:

import pandas as pd

values = {'dates':  ['20190902101010','20190913202020','20190921010101'],
          'status': ['Opened','Opened','Closed']
          }

df = pd.DataFrame(values, columns = ['dates','status'])

df['dates_datetime'] = pd.to_datetime(df['dates'], format='%Y%m%d%H%M%S')

df['dates_datetime_tz'] = df.dates_datetime.dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')

print (df)
print (df.dtypes)

Result:

            dates  status      dates_datetime         dates_datetime_tz
0  20190902101010  Opened 2019-09-02 10:10:10 2019-09-02 15:40:10+05:30
1  20190913202020  Opened 2019-09-13 20:20:20 2019-09-14 01:50:20+05:30
2  20190921010101  Closed 2019-09-21 01:01:01 2019-09-21 06:31:01+05:30

I've converted from UTC to a specific TZ, you can choose any other you need.

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