Parsing date string in python (convert string to date)

I have a datetime string as a string like:

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

How to treat this string as a datetime object.

I read the following documentation:

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

BUt I get an 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'm not sure how to read this format.

Any suggestions. Thanks

Edit: Also, I have to add, all I care about is part of the date

+5
source share
1 answer

The standard datetime.datetime.strptime has problems with time zone 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 only need a part of the date, 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)
+23
source

All Articles