dateutil.parser.parse() and lost timezone information

微笑、不失礼 提交于 2019-12-04 06:23:33

timezone.now will give you an aware datetime object if USE_TZ is true. You don't need to parse it further.

In this example, USE_TZ is True, and the timezone is set to UTC:

>>> from django.utils import timezone as djtz
>>> i = djtz.now()
>>> type(i)
<type 'datetime.datetime'>
>>> i.tzinfo
<UTC>

As far as dateutil goes, it will parse your string correctly:

>>> from dateutil.parser import parse
>>> s = '2014-07-14 08:51:49.123342+00:00'
>>> parse(s).tzinfo
tzutc()
>>> z = parse(s)
>>> z
datetime.datetime(2014, 7, 14, 8, 51, 49, 123342, tzinfo=tzutc())

You can see its picking up the correct timezone (UTC in this case).

The default format specifiers only accept +0000 as the offset format with %z, or the three letter timezone name with %Z; but you cannot use this to parse, only to format:

>>> datetime.datetime.strptime('2014-07-14 08:51:49.123342+0000', '%Y-%m-%d %H:%M:%S.%f%z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/_strptime.py", line 317, in _strptime
    (bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S.%f%z'
>>> datetime.datetime.strftime(z, '%Z')
'UTC'
>>> datetime.datetime.strftime(z, '%z')
'+0000'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!