1

How would you convert a string of an aware datetime back to the datetime instance?

This is my try:

>>> my_date = datetime.datetime(2017, 5, 19, 21, tzinfo=timezone(timedelta(hours=1)))
>>> string = str(my_date)
>>> string
'2017-05-19 21:00:00+01:00'
>>> datetime.strptime(string, "%Y-%m-%d %H:%M:%S%z")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/_strptime.py", line 565, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.6/_strptime.py", line 362, in _strptime
    (data_string, format))
ValueError: time data '2017-05-19 21:00:00+01:00' does not match format '%Y-%m-%d %H:%M:%S%z'

The : obviously doesn't match %z. I've spent an unhealthy amount of time trying to figure this out, trying to remove : char from the string which didn't help and I have no clue why.

Nicolás Ozimica
  • 9,481
  • 5
  • 38
  • 51
Thyrst'
  • 2,253
  • 2
  • 22
  • 27
  • 2
    You may find your answer here: http://stackoverflow.com/questions/28331512/how-to-convert-python-isoformat-string-back-into-datetime-object http://stackoverflow.com/questions/466345/converting-string-into-datetime http://stackoverflow.com/questions/13182075/how-to-convert-a-timezone-aware-string-to-datetime-in-python-without-dateutil – Loïc Poncin Feb 22 '17 at 15:32
  • Yeah. `python-dateutil` module works well, thanks ;) – Thyrst' Feb 22 '17 at 21:08

0 Answers0