Function Name:
astimezone
Function Signature:
astimezone(tz=None)
Function Overview:
- The function astimezone() returns a datetime instance with time zone information as specified by tz parameter.
- The new datetime instance returned by astimezone() will have the new UTC offset value as per the tz parameter.
- If the method astimezone()is called without the tz parameter then the datetime object will have the local date, time and the time zone.
- It is a known behavior that while printing the UTC offset value of a time zone west of UTC the output is printer as -1 instead of actual number of hours:minutes:seconds
Example:
import datetime
#Singapore Time sgtTimeDelta = datetime.timedelta(hours=8) sgtTZObject = datetime.timezone(sgtTimeDelta, name="SGT")
#Japan Standard Time jstTimeDelta = datetime.timedelta(hours=9) jstTZObject = datetime.timezone(jstTimeDelta, name="JST")
d1 = datetime.datetime(2017,2,14,12,00,00,00,sgtTZObject) d2 = d1.astimezone(jstTZObject)
# call astimezone() without any tz object d3 = d2.astimezone()
print("Singapore time from a datetime instance:{}".format(d1)) print("UTC offset for Singapore:{}".format(d1.utcoffset())) print("Corresponding Tokyo datetime:{}".format(d2)) print("UTC offset for Singapore:{}".format(d2.utcoffset())) print("Corresponding local datetime :{}".format(d3)) print("UTC offset for local:{}".format(d3.utcoffset())) |
Output:
Singapore time from a datetime instance:2017-02-14 12:00:00+08:00 UTC offset for Singapore:8:00:00 Corresponding Tokyo datetime:2017-02-14 13:00:00+09:00 UTC offset for Singapore:9:00:00 Corresponding local datetime :2017-02-13 23:00:00-05:00 UTC offset for local:-1 day, 19:00:00 |