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?

5
  • I'm getting the right information. Not sure where the problem might be. Could it be from your localtime()? Commented Jun 23, 2015 at 14:11
  • 1
    Do you compensate for Daylight Saving Time? Commented Jun 23, 2015 at 14:12
  • Anthon, how should I go about compensating for DST? Thanks. Commented Jun 23, 2015 at 14:14
  • Is it consistently 1 hour off? If so, why not just add (or subtract) an extra hour? Commented Jun 23, 2015 at 14:14
  • HandyPete, it is consistently off since I started trying this yesterday. I considered adding an hour, but it seems like a brittle solution, likely to break on DST changes. Commented Jun 23, 2015 at 14:18

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.