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 :
Syntax
Syntax: Series.dt.tz_localize((tz, ambiguous=’raise’, nonexistent=’raise’)
Parameter:
- tz: Time zone to convert timestamps to
- ambiguous: determines whether the time should be interpreted as wall time (default), the version of the time that was earlier, the version of the time that was later, or raise an error if ambiguous
- non-existent: determines whether the time should be shifted forward to the closest existing time, shifted backward to the closest existing time, return NaT, or raise an error if nonexistent
Returns: same type as self
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.
Contact Us