5

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'
0

4 Answers 4

8

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

0

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...

1 Comment

This appears to be your library. The typical site courtesy is to provide a note to that effect, e.g. "note: I am the author of the library". It'd also be nice to see a few words about what this library does, and why it's preferable to using the native code provided in other answers. What's "easy" here exactly? Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.