python get timezone value from datetime object

Viewed 12071

Does anyone know how to obtain the Timezone value (in minutes, hrs etc.) of an ISO8601 timestamp? I can see it in a tzinfo object, but can't seem to get the value out. Here's what I've done so far, but how do I get the the value -28800 out into a variable?

import dateutil.parser
import datetime
firststarttime = '2008-12-31T23:00:00-08:00'
datetime_obj = dateutil.parser.parse(firststarttime)
datetime_obj
Out[57]: datetime.datetime(2008, 12, 31, 23, 0, tzinfo=tzoffset(None, -28800))
datetime_obj.tzinfo
Out[46]: tzoffset(None, -28800)
2 Answers

Just use (if you're on Python 2.7 or above):

datetime_obj.utcoffset().total_seconds()

Using utcoffset() to get the timedelta, and total_seconds() to convert to seconds. You can read the documentation linked for information about what exactly they're doing.

If you need to add this offset onto some other datetime, then you can just use utcoffset() to get back a timedelta. Though the return value might look a bit strange:

datetime.timedelta(-1, 57600)  # equivelant to datetime.timedelta(seconds=-28800)

This is because of the way timedelta normalizes negative values which is also noted at datetime.timedelta.

the problem is, that the values seem to be fixed to that object. this is not the most efficient way to do it, in fact, I would happily know other answers, but, this is how I'd do it:

import dateutil.parser
import datetime
import re
firststarttime = '2008-12-31T23:00:00-08:00'
datetime_obj = dateutil.parser.parse(firststarttime)
s = str(datetime_obj.tzinfo)
p = re.compile(",\s.?\d+")
result = p.search(s).group()
result = int(result[2:])

prints

print(result)
>>> -28800 # as integer
Related