Dateutil.parser.parse () and lost timezone information

I am trying dateutil.parser.parse() parse the default output of str(datetime.datetime.now()) using dateutil.parser.parse() related data. However, parse() seems to lose timezone information and replace it with the local timezone. The following is the output of IPython:

 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 

As far as I understand, dateutil does some heuristics when guessing the date format, and this may go wrong.

  • How to provide an accurate date and time format for parsing time associated with a time zone?

  • Even better - if the format is known as parsing this datetime using only Python stdlib, without dateutil dependencies?

+6
source share
1 answer

timezone.now will provide you with a aware datetime object if USE_TZ true . You do not need to disassemble it further.

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

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

As for dateutil, 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 how he is dialing the correct time zone (UTC in this case).

format specifiers by default only accept +0000 as the offset format using %z or the three letter timezone name with %z ; but you cannot use this for parsing, only for formatting:

 >>> 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' 
-2
source

Source: https://habr.com/ru/post/972162/


All Articles