简体   繁体   中英

Python convert date string to datetime

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'

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)

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM