Search code examples
pythondatetimetimezoneutc

Converting UTC time to dynamic timezones


I want to convert the UTC timestamp given as 1623715897 and the timezone value as 19800 to the time in '%H:%M:%S'. I got this information from open weather API and I did not know how to convert to the given time including timezone value.

I used this code but got the time in UTC.

from datetime import datetime
ts = 1623715897
tz = 19800
datetime.utcfromtimestamp(ts).strftime('%H:%M:%S')

I am not finding the solution for using tz (timezone) value.


Solution

  • You need to utilize timezone and timedelta from datetime

    from datetime import datetime, timezone, timedelta
    ts = 1623715897
    tz = 19800
    >>> datetime.utcfromtimestamp(ts).strftime('%H:%M:%S')
    '00:11:37'
    
    >>> datetime.fromtimestamp(ts, tz=timezone(timedelta(seconds=19800))).strftime('%H:%M:%S')
    '05:41:37'