Related Articles

Related Articles

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output :

Now we want to convert the naive DatetimeIndex object into a timezone aware object

filter_none

edit
close

play_arrow

link
brightness_4
code

# make timezone aware
didx.tz_localize(tz ='Europe/Berlin')

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output :

Now we want to convert the naive DatetimeIndex object into a timezone aware object

filter_none

edit
close

play_arrow

link
brightness_4
code

# make timezone aware
didx.tz_localize(tz ='US/Eastern')

chevron_right


Output :

As we can see in the output, the function has introduced timezone awareness into the didx object.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :