Tuesday, November 19, 2024
Google search engine
HomeLanguagesPython | Pandas Timestamp.astimezone

Python | Pandas Timestamp.astimezone

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.astimezone() function convert tz-aware Timestamp to another time zone. For tz-naive Timestamp object the function throws an error.

Syntax : Timestamp.astimezone()

Parameters :
tz : Time zone for time which Timestamp will be converted to.

Return : converted : Timestamp

Example #1: Use Timestamp.astimezone() function to change the timezone of the given object to ‘Europe/Berlin’.




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


Output :

Now we will use the Timestamp.astimezone() function to change the timezone of the ts object to the desired timezone.




# change the timezone to 'Europe/Berlin'
ts.astimezone('Europe/Berlin')


Output :

As we can see in the output, the Timestamp.astimezone() function has changed the timezone of the given Timestamp object from ‘US/Central’ to ‘Europe/Berlin’.

Example #2: Use Timestamp.astimezone() function to change the timezone of the given object to ‘Asia/Calcutta’.




# 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, tz = 'Europe/Berlin')
  
# Print the Timestamp object
print(ts)


Output :

Now we will use the Timestamp.astimezone() function to change the timezone of the ts object to the desired timezone.




# change the timezone to 'Asia / Calcutta'
ts.astimezone('Asia/Calcutta')


Output :

As we can see in the output, the Timestamp.astimezone() function has changed the timezone of the given Timestamp object from ‘Europe/Berlin’ to ‘Asia/Calcutta’.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments