Python | Pandas DatetimeIndex.tz_localize()
Last Updated :
24 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas DatetimeIndex.tz_localize()
function localize tz-naive DatetimeIndex to tz-aware DatetimeIndex. This method takes a time zone (tz) naive DatetimeIndex object and makes this time zone aware. It does not move the time to another time zone. Time zone localization helps to switch from time zone aware to time zone unaware objects.
Syntax: DatetimeIndex.tz_localize(tz, ambiguous=’raise’, errors=’raise’)
Parameters :
tz : Time zone to convert timestamps to tz-aware DatetimeIndex. Passing None will remove the time zone information preserving local time.
ambiguous : str {‘infer’, ‘NaT’, ‘raise’} or bool array, default ‘raise’
errors : {‘raise’, ‘coerce’}, default ‘raise’
Return : Index converted to the specified time zone.
Example #1: Use DatetimeIndex.tz_localize()
function to make the naive DatetimeIndex object to an object that is time zone aware.
import pandas as pd
didx = pd.DatetimeIndex(start = '2000-01-15 08:00' , freq = 'Q' , periods = 4 )
print (didx)
|
Output :
Now we want to convert the naive DatetimeIndex object into a timezone aware object
didx.tz_localize(tz = 'Europe/Berlin' )
|
Output :
As we can see in the output, the function has introduced timezone awareness into the didx object.
Example #2: Use DatetimeIndex.tz_localize()
function to make the naive DatetimeIndex object to an object that is time zone aware.
import pandas as pd
didx = pd.DatetimeIndex(start = '2014-08-01 10:05:45' , freq = 'D' , periods = 5 )
print (didx)
|
Output :
Now we want to convert the naive DatetimeIndex object into a timezone aware object
didx.tz_localize(tz = 'US/Eastern' )
|
Output :
As we can see in the output, the function has introduced timezone awareness into the didx object.
Share your thoughts in the comments
Please Login to comment...