How to convert the hour difference in timezone info to the abbreviated timezone name

33 Views Asked by At

This is a followup question to

How can I convert the time stamp with timezone info to utc time in python

I was able to get the time string like this "2023-09-06T22:02:44-07:00" through calling

datetime.now().astimezone().isoformat(timespec='seconds')

I wonder whether there is a way to get the time string like "2023-09-06T22:02:44-PDT"? And also convert the time string to UTC time -- something like "2023-09-07T05:02:44-UTC"? Thanks!

1

There are 1 best solutions below

0
Henry On

Get the timezone-naive timestamp and append the timezone-aware tzname to get your desired format

now = datetime.now()
print(now.isoformat(timespec="seconds") + "-" + now.astimezone().tzname())

or use strftime with %Z

datetime.now().astimezone().strftime("%Y-%m-%dT%H:%M:%S-%Z")