1

I am getting value error while converting string to datetime. Can anyone please help to resolve this issue.

>>> from datetime import datetime
>>> date_str = "2018-07-13T17:12:02-0500"
>>> t = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%z")

Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
t = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%z")
File "C:\Python27\lib\_strptime.py", line 324, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S%z'

>>> t = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%Z")

Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
t = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%Z")
File "C:\Python27\lib\_strptime.py", line 332, in _strptime
(data_string, format))
ValueError: time data '2018-07-13T17:12:02-0500' does not match format '%Y- 
%m-%dT%H:%M:%S%Z'
>>>

I am using python version 2.7.14

user2251503
  • 197
  • 5
  • 13

1 Answers1

1
from datetime import datetime
iso_ts = '2012-11-01T04:16:13-04:00'
datetime.strptime(''.join(iso_ts.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2012, 11, 1, 4, 16, 13, 
tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))
  • am using python 2.7 version... am getting same value error.. – user2251503 Sep 28 '18 at 05:48
  • 2
    While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find [how to write a good answer](https://stackoverflow.com/help/how-to-answer) very helpful. Please edit your answer. – hellow Sep 28 '18 at 07:10