Search code examples
pythontimezonepytz

Python - get UTC offset by seconds


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


Solution

  • >>> 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