Reputation: 7288
Might seem very easy for others but I couldn't find a way to get only the seconds from the timezone
>>> import datetime
>>> dstr = '2017-06-20T19:40+02:00'
>>> from dateutil.parser import parse
>>> dt = parse(dstr)
>>> dt
datetime.datetime(2017, 6, 20, 19, 40, tzinfo=tzoffset(None, 7200))
How to get only the 7200 (with - sign as well for negative, if it is negative) from the tzoffset object? I couldn't find the documentation for the tzoffset in python.
Upvotes: 1
Views: 1581
Reputation: 1121216
The timezone is a separate object from the dateutil
project, see dateutil.tz.offset
:
>>> dt.tzinfo
tzoffset(None, 7200)
>>> type(dt.tzinfo)
<class 'dateutil.tz.tz.tzoffset'>
The official API is to use the tzinfo.utcoffset()
method, passing in the datetime
instance:
>>> dt.tzinfo.utcoffset(dt)
datetime.timedelta(0, 7200)
>>> dt.tzinfo.utcoffset(dt).seconds
7200
The documentation doesn't specify any attributes for the dateutil.tz.offset
object; it is not designed for direct interrogation. If you don't want to use the tzinfo.utcoffset()
method, then dir()
reveals what we can access:
>>> from pprint import pprint
>>> pprint(dir(dt.tzinfo))
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'_name',
'_offset',
'dst',
'fromutc',
'is_ambiguous',
'tzname',
'utcoffset']
The _offset
attribute is a datetime.timedelta()
object:
>>> dt.tzinfo._offset
datetime.timedelta(0, 7200)
>>> dt.tzinfo._offset.seconds
7200
The attribute is an implementation detail, so be careful not to rely too much on it.
Upvotes: 4
Reputation: 3591
This seems to work as well :
dt.tzinfo.utcoffset(dt).total_seconds()
Out[23]: 7200.0
Upvotes: 2
Reputation: 980
import datetime
dstr = '2017-06-20T19:40+02:00'
from dateutil.parser import parse
dt = parse(dstr)
print(dt.timetz().utcoffset().seconds)
7200
detail see: time.tzinfo
Upvotes: 0