3

Based on this code, how do I get the UTC offset of a given date by seconds. Get UTC offset from time zone name in python

Currently, I have this code:

Python 2.7.3 (default, Jul  3 2012, 19:58:39) 
[GCC 4.7.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pytz
>>> import datetime
>>> offset = datetime.datetime.now(pytz.timezone('US/Pacific')).strftime('%z')
>>> offset
'-0700'
>>> int(offset)*3600
-2520000
>>> int(offset)*360 
-252000
>>> 

For example, US/Pacific sometimes is -800 hours (probably military time :D) but I need it to be in seconds, ex: -25200.

Shall I just multiply it by 360? Doesn't sound right but who knows.

TIA

Community
  • 1
  • 1
Lysender
  • 179
  • 1
  • 2
  • 14

1 Answers1

9
>>> import datetime, pytz
>>> melbourne = pytz.timezone("Australia/Melbourne")
>>> melbourne.utcoffset(datetime.datetime.now())
datetime.timedelta(0, 36000)

>>> pacific = pytz.timezone("US/Pacific")
>>> pacific.utcoffset(datetime.datetime.now())
datetime.timedelta(-1, 61200)
>>> -1*86400+61200
-25200
>>> pacific.utcoffset(datetime.datetime.now()).total_seconds()
-25200.0
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • 1
    won't `.total_seconds()` help here? :-) – Martijn Pieters Sep 10 '12 at 06:24
  • @MartijnPieters, yep, especially if the offset has a fractional number of seconds :) – John La Rooy Sep 10 '12 at 06:26
  • Ach, call `int()` on it and be done with it; timedeltas can deal with milliseconds and `.total_seconds()` reflects that. :-P – Martijn Pieters Sep 10 '12 at 06:28
  • Beware that if the server is using a timezone other than the one given than this produces incorrect results during the daylight savings time switch over. The datetime passed to `timezone.utcoffset` is assumed to be local to that time zone and will fail if passed either the hour that daylight savings begins or ends. `datetime.datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Australia/Melbourne')).utcoffset().total_seconds()` is a better approach. – Nathan Villaescusa Nov 06 '16 at 22:16
  • `datetime.datetime.now(pytz.timezone('Australia/Melbourne')).utcoffset().total_seconds()` works too. – Nathan Villaescusa Nov 06 '16 at 22:23