Issues with datetime and UTC offset

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

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.

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

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 “”, line 1, in
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’

Yes! Seems to work with Python3. Thanks.

// Tony