getting time zone offset in seconds in Python

741 views Asked by At

I need to discover the timezone offset in seconds from UTC. Here's what I am trying now:

timeZoneSecondsOffset = calendar.timegm(time.gmtime()) - calendar.timegm(time.localtime())

This works - kind of. It gives a value that is off by one hour. How can I get a more accurate result?

1

There are 1 answers

0
Robᵩ On

This works for me:

import datetime
import time

for ts in 1435071821, 1419519821: # roughly, now and 6 months ago
                                  # as reported by time.time()

    now = datetime.datetime.fromtimestamp(ts)
    utcnow = datetime.datetime.utcfromtimestamp(ts)
    offset = (now - utcnow).total_seconds()

    now = datetime.datetime.isoformat(now)
    utcnow = datetime.datetime.isoformat(utcnow)

    print now, utcnow, offset

Result when run on my PC in the US central time zone:

2015-06-23T10:03:41 2015-06-23T15:03:41 -18000.0
2014-12-25T09:03:41 2014-12-25T15:03:41 -21600.0