问题描述
我正在尝试 dateutil.parser.parse()
来解析默认的 str(datetime.datetime.now())
输出使用时区感知数据时间。但是, parse()
似乎丢失了时区信息,并将其替换为本地时区。以下是IPython输出:
I am trying to dateutil.parser.parse()
to parse the default str(datetime.datetime.now())
output using timezone-aware datetimes. However, parse()
seems to lose the timezone information and replace it with the local time timezone. Below is the IPython output:
In [1]: from django.utils.timezone import now
In [3]: import dateutil
In [4]: t = now()
In [6]: print t
2014-07-14 08:51:49.123342+00:00
In [7]: st = unicode(t)
In [8]: print dateutil.parser.parse(st)
2014-07-14 08:51:49.123342+02:00
到目前为止,我了解 dateutil
某些heurestics在猜测日期格式,可能会出现错误。
As far I understood dateutil
does some heurestics when guessing the date format and it might go wrong here.
-
如何给出精确的datetime格式解析时区感知datetimes?
How to give exact datetime format for parsing timezone-aware datetimes?
更好的 - 如果格式是已知的如何解析这个datetime只使用Python stdlib,没有dateutil依赖?
Even better - if the format is known how to parse this datetime using only Python stdlib, without dateutil dependency?
推荐答案
timezone.now
。您不需要进一步解析。
timezone.now
will give you an aware datetime object if USE_TZ
is true. You don't need to parse it further.
在此示例中,USE_TZ为True,时区设置为UTC:
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>
至于dateutil,它会正确解析你的字符串:
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())
您可以看到它拾起正确的时区(在这种情况下为UTC)。
You can see its picking up the correct timezone (UTC in this case).
只接受+0000作为偏移格式,% z
,或三字母的时区名称与%Z
;但是您不能使用这个来解析,只能使用格式:
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'
这篇关于dateutil.parser.parse()和丢失的时区信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!