How to Convert a tz-Naive DateTime Series to tz-Aware DateTime Series
To convert a naive DateTime series to an aware DateTime series we use the dt.tz_localize() method of the Pandas library in Python.
Let’s understand it better with an example:
Example
Use the Series.dt.tz_localize() function to return the given series object as an array of native Python DateTime objects.
Python3
# importing pandas as pd import pandas as pd # Creating the Series sr = pd.Series(pd.date_range( '2012-12-31 00:00' , periods = 5 , freq = 'D' )) # Creating the index idx = [ 'Day 1' , 'Day 2' , 'Day 3' , 'Day 4' , 'Day 5' ] # set the index sr.index = idx # Print the series print (sr) |
Output :
Now we will use the Series.dt.tz_localize() function to localize the given tz-naive series to ‘Europe/Berlin’.
Python3
# localize to 'Europe / Berlin' result = sr.dt.tz_localize(tz = 'Europe / Berlin' ) # print the result print (result) |
Output :
As we can see in the output, the dt.tz_localize() function has successfully localized the given tz-naive datetime series to tz-aware.
Pandas Series dt.tz_localize() | Convert tz-Naive DateTime to tz-Aware
The dt.tz_localize() method converts the time zone (tz)-naive Datetime Series object into a tz-aware Datetime Series.
It does not move the time to another time zone.
Example:
Python3
import pandas as pd sr = pd.Series([ '2012-12-31' , '2019-1-1 12:30' , '2008-02-2 10:30' , '2010-1-1 09:25' , '2019-12-31 00:00' ]) idx = [ 'Day 1' , 'Day 2' , 'Day 3' , 'Day 4' , 'Day 5' ] sr.index = idx sr = pd.to_datetime(sr) result = sr.dt.tz_localize(tz = 'US / Eastern' ) print (result) |
Output :