Python | Pandas Timestamp.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 Timestamp.tz_localize() function convert naive Timestamp to local time zone, or remove timezone from tz-aware Timestamp.

Syntax :Timestamp.tz_localize()

Parameters :
tz : Time zone for time which Timestamp will be converted to. None will remove timezone holding local time.
ambiguous : bool, ‘NaT’, default ‘raise’
errors : ‘raise’, ‘coerce’, default ‘raise’

Return : localized : Timestamp

Example #1: Use Timestamp.tz_localize() function to convert a tz-aware Timestamp to a naive Timestamp object.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas as pd
import pandas as pd
  
# Create the Timestamp object
ts = pd.Timestamp(year = 2011,  month = 11, day = 21
                  hour = 10, second = 49, tz = 'US/Central'
  
# Print the Timestamp object
print(ts)

chevron_right


Output :

Now we will use the Timestamp.tz_localize() function to convert the tz-aware Timestamp to naive Timestamp.

filter_none

edit
close

play_arrow

link
brightness_4
code

# convert to naive Timestamp
ts.tz_localize(tz = None)

chevron_right


Output :

As we can see in the output, the Timestamp.tz_localize() function has converted the given Timestamp to a naive Timestmap.
 
Example #2: Use Timestamp.tz_localize() function to convert the given naive Timestamp to tz-aware Timestamp object. Set the timezone to ‘US/Pacific’.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas as pd
import pandas as pd
  
# Create the Timestamp object
ts = pd.Timestamp(year = 2009, month = 5, day = 31
                             hour = 4, second = 49)
  
# Print the Timestamp object
print(ts)

chevron_right


Output :

Now we will use the Timestamp.tz_localize() function to set the timezone of ts object to ‘US/Pacific’.

filter_none

edit
close

play_arrow

link
brightness_4
code

# set to 'US / Pacific'
ts.tz_localize(tz = 'US/Pacific')

chevron_right


Output :

As we can see in the output, the Timestamp.tz_localize() function has set the timezone of the given object to ‘US/Pacific’.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.