Python | Pandas DatetimeIndex.tz_localize()
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.
# importing pandas as pd import pandas as pd # Create the DatetimeIndex # Here 'Q' represents quarter end frequency didx = pd.DatetimeIndex(start = '2000-01-15 08:00' , freq = 'Q' , periods = 4 ) # Print the DatetimeIndex print (didx) |
Output :
Now we want to convert the naive DatetimeIndex object into a timezone aware object
# make timezone aware 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.
# importing pandas as pd import pandas as pd # Create the DatetimeIndex # Here 'D' represents calendar day frequency didx = pd.DatetimeIndex(start = '2014-08-01 10:05:45' , freq = 'D' , periods = 5 ) # Print the DatetimeIndex print (didx) |
Output :
Now we want to convert the naive DatetimeIndex object into a timezone aware object
# make timezone aware didx.tz_localize(tz = 'US/Eastern' ) |
Output :
As we can see in the output, the function has introduced timezone awareness into the didx object.
Contact Us