简体   繁体   中英

parsing date string in python (convert string to date)

I have a datetime string in the form of a string as:

2011-10-23T08:00:00-07:00

How do i parse this string as the datetime object.

I did the following reading the documentation:

date = datetime.strptime(data[4],"%Y-%m-%d%Z")

BUt I get the error

  ValueError: time data '2011-10-23T08:00:00-07:00' does not match format '%Y-%m-%d%Z'

which is very clear.

But I am not sure how to read this format.

Any suggestions. Thanks

Edit: Also, I must add, all I care about is the date part

Standard datetime.datetime.strptime has problems with timezone definitions. Use dateutil.parser

>>> from dateutil import parser
>>> parser.parse("2011-10-23T08:00:00-07:00")
datetime.datetime(2011, 10, 23, 8, 0, tzinfo=tzoffset(None, -25200))

If you care about the date part only, you can try it without dateutil.parser:

>>> from datetime import datetime
>>> datetime.strptime(data[4].partition('T')[0], '%Y-%m-%d').date()
datetime.date(2011, 10, 23)

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