Python | Pandas Timestamp.tz_localize
Last Updated :
09 Dec, 2021
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.
Python3
import pandas as pd
ts = pd.Timestamp(year = 2011 , month = 11 , day = 21 ,
hour = 10 , second = 49 , tz = 'US/Central' )
print (ts)
|
Output :
Now we will use the Timestamp.tz_localize() function to convert the tz-aware Timestamp to naive Timestamp.
Python3
ts.tz_localize(tz = None )
|
Output :
As we can see in the output, the Timestamp.tz_localize() function has converted the given Timestamp to a naive Timestamp.
Example #2: Use Timestamp.tz_localize() function to convert the given naive Timestamp to tz-aware Timestamp object. Set the timezone to ‘US/Pacific’.
Python3
import pandas as pd
ts = pd.Timestamp(year = 2009 , month = 5 , day = 31 ,
hour = 4 , second = 49 )
print (ts)
|
Output :
Now we will use the Timestamp.tz_localize() function to set the timezone of ts object to ‘US/Pacific’.
Python3
ts.tz_localize(tz = 'US/Pacific' )
|
Output :
As we can see in the output, the Timestamp.tz_localize() function has set the timezone of the given object to ‘US/Pacific’.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...