0

Can't convert a string into a DateTime object in Python3.8.5.

>>> from datetime import datetime
>>> x = "2020-06-27T16:03:00+0000"

Variations of formats I have tried after referencing:

'%Y-%m-%dT%H:%M:%S.000%z'
'%Y-%m-%dT%H:%M:%S.f%z'
'%Y-%m-%dT%H:%M:%S+%z'

I tried a bunch of other combinations that did not make a lot of sense. I need the Zulu time added as my code deals with sorting a bunch of events from international tracking.

Everything I've seen has been about Python2.7 having issues with Zulu time formats.

SOLVED: Zulu time includes the + and the - therefore

'%Y-%m-%dT%H:%M:%S%z'

is the correct format. Will answer when I can for a brief answer for others

funie200
  • 3,688
  • 5
  • 21
  • 34
Kyle Calica-St
  • 2,629
  • 4
  • 26
  • 56
  • Does this answer your question? [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Jul 30 '20 at 10:30

3 Answers3

2

The + sign is part of the timezone offset, so the format string doesn't need to contain + sign

>>> from datetime import datetime
>>> x = "2020-06-27T16:03:00+0000"
>>>
>>> datetime.strptime(x, '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2020, 6, 27, 16, 3, tzinfo=datetime.timezone.utc)
Prem Anand
  • 2,469
  • 16
  • 16
1

You can use dateutil library

In [15]: from dateutil import parser

In [16]: x = "2020-06-27T16:03:00+0000"

In [17]: parser.parse(x)
Out[17]: datetime.datetime(2020, 6, 27, 16, 3, tzinfo=tzutc())
bigbounty
  • 16,526
  • 5
  • 37
  • 65
1

With Python 3.7+, you could also use fromisoformat. It requires a str.replace but might be faster.

from datetime import datetime
x = "2020-06-27T16:03:00+0000"
dt = datetime.fromisoformat(x.replace('+0000', '+00:00'))
print(repr(dt))
>>> datetime.datetime(2020, 6, 27, 16, 3, tzinfo=datetime.timezone.utc)
FObersteiner
  • 22,500
  • 8
  • 42
  • 72