Issues with datetime and UTC offset

38 views
Skip to first unread message

Tony Högsten

unread,
Apr 7, 2020, 4:37:26 AM4/7/20
to Ansible Development
Hi!

I have a date that I get from some source (I cannot change the source data), that looks like this: "Tue, 07 Apr 2020 08:16:10 +0000". So I need to convert it to another datetime format. 

The approach I took was I attempted to make it to datetime, but it doesn't seem possible. 

"{{ item.last_report_time | to_datetime('%a, %d %b %Y %H:%M:%S +%z') | default(omit) }}"

If I do this I get the error:

and could not be converted to an dict.The error was: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S +%z'

If I omit the z i get the following error:

to_datetime('%a, %d %b %Y %H:%M:%S') }}\"}), and could not be converted to an dict.The error was: unconverted data remains:  +0000


i'm also looping the results I get from an earlier step, so I am a bit hindered in my possibility of running a block of code to change the datetime. As far as I understand it, it needs to be done within the loop itself.

body_dict:
  agentVersion
: "{{ item.agent_version }}"
  agentType
: "{{ item.agent_type }}"
  lastReportTime
: "{{ item.last_report_time | to_datetime('%a, %d %b %Y %H:%M:%S +%z') | default(omit) }}"
with_items
: "{{ result.output }}"


Any ideas?

Best regards,
Tony

Florian Apolloner

unread,
Apr 7, 2020, 1:21:01 PM4/7/20
to Ansible Development
to_datetime directly calls into strptime. That said I'd just drop the +, %z should include that already: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

If you still get an error then, something is wonky.

Tony Högsten

unread,
Apr 8, 2020, 8:51:39 AM4/8/20
to Ansible Development
Hi, 

I've tried with and without the '+'. It complains on the z specifically. 

I get the exact same error as I wrote before.

//Tony

Florian Apolloner

unread,
Apr 12, 2020, 5:11:43 PM4/12/20
to Ansible Development
I get that error on Python 2, but Python 3 works fine. Given that Python 2 is EOL you probably want to update to Python 3.

py3:
In [22]: datetime.datetime.strptime('Sun, 12 Apr 2020 23:04:52 +0000', '%a, %d %b %Y %H:%M:%S %z')                                                                                                                                           
Out[22]: datetime.datetime(2020, 4, 12, 23, 4, 52, tzinfo=datetime.timezone.utc)

py2:
>>> datetime.datetime.strptime('Sun, 12 Apr 2020 23:04:52 +0000', '%a, %d %b %Y %H:%M:%S %z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/_strptime.py", line 324, in _strptime
    (bad_directive, format))
ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z'

Tony Högsten

unread,
Apr 22, 2020, 8:31:08 AM4/22/20
to Ansible Development
Yes! Seems to work with Python3. Thanks.

// Tony
Reply all
Reply to author
Forward
0 new messages