Ariel
Ariel

Reputation: 988

Pandas how to convert the timezone for a column

In my pandas dataframe I need to convert the CREATED column from UTC time to Asia/Hong_Kong (8 hour difference). I need to use pytz, instead of declaring + 8 hours. I am aware dt can accomplish this, however for this script the new version of pandas cannot be used.

ID          CREATED
234         2017-03-16 17:18:20
720         2017-03-15 22:09:13    
639         2017-03-16 04:49:12

I am able to localize the CREATED column, however I am not having any luck on the conversion part.

import pytz
tz_utc = pytz.timezone('UTC')
tz_hkg = pytz.timezone('Asia/Hong_Kong')

def localize_utc(x):
    if not isinstance(x, pd.tslib.NaTType):
        return tz_utc.localize(x) 
    return None

df['CREATED'] = df['CREATED'].apply(lambda x: localize_utc(x))

Any help greatly appreciated!

Upvotes: 3

Views: 2099

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210962

Assuming we have the following DF:

In [31]: df
Out[31]:
    ID             CREATED
0  234 2017-03-16 17:18:20
1  720 2017-03-15 22:09:13
2  639 2017-03-16 04:49:12

we can convert TZ as follows:

In [32]: df['CREATED'].dt.tz_localize('UTC').dt.tz_convert('Asia/Hong_Kong')
Out[32]:
0   2017-03-17 01:18:20+08:00
1   2017-03-16 06:09:13+08:00
2   2017-03-16 12:49:12+08:00
Name: CREATED, dtype: datetime64[ns, Asia/Hong_Kong]

Upvotes: 4

Related Questions