0

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?

Anthon
  • 69,918
  • 32
  • 186
  • 246
Casey Perkins
  • 1,853
  • 2
  • 23
  • 41

1 Answers1

0

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
Robᵩ
  • 163,533
  • 20
  • 239
  • 308