Reputation: 20906
Im trying to convert a date string into Python but get errors -
String: '1986-09-22T00:00:00'
dob_python = datetime.strptime('1986-09-22T00:00:00' , '%Y-%m-%d%Z%H-%M-%S').date()
Error:-
ValueError: time data '1986-09-22T00:00:00' does not match format '%Y-%m-%d%Z%H-%M-%S'
Upvotes: 5
Views: 7913
Reputation: 4465
You can use easy_date to make it easy:
import date_converter
dob_python = date_converter.string_to_date('1986-09-22T00:00:00', '%Y-%m-%dT%H:%M:%S')
Note: I am the author of the library
The library makes it easy because you only need to think about which type you want, e.g.: string_to_date
, date_to_datetime
, string_to_timestamp
and so on...
Upvotes: 0
Reputation: 2965
Notice your corresponding format string -- otherwise it will be error.
from datetime import datetime
datetime.strptime('1986-09-22T01:02:03', '%Y-%m-%dT%H:%M:%S').date()
#datetime.date(1986, 9, 22)
1986
matchs %Y
09
matchs %m
22
matchs %d
01
matchs %H
02
matchs %M
03
matchs %S
In detail, you can refer python document. It has clear description and example.
https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
Upvotes: 1
Reputation: 28313
The dateutil
module greatly simplifies work when dealing with datetimes in python.
Using dateutil, you date could be formatted like this:
>>> import dateutil.parser as dateparser
>>> dob_python = dateparser.parse('1986-09-22T00:00:00')
>>> dob_python.date()
datetime.date(1986, 9, 22)
The parse function takes an optional parameter parseinfo
for more complex or ambiguous string representations, but for the standard-ish date-string that you have, additional arguments are not needed.
Upvotes: 1
Reputation: 1124488
T
is not a timezone. It is just a separator. Don't use %Z
to try and parse it, use a literal T
. Your time separators must match as well; you need to look for :
colons, not dashes:
dob_python = datetime.strptime('1986-09-22T00:00:00', '%Y-%m-%dT%H:%M:%S').date()
# ^ ^ ^
Demo:
>>> from datetime import datetime
>>> datetime.strptime('1986-09-22T00:00:00', '%Y-%m-%dT%H:%M:%S').date()
datetime.date(1986, 9, 22)
Upvotes: 8