Possible Duplicate:
Parsing Dates and Times from Strings using python
I'm reading a string
"2011-06-11"
How can I cast this to a date object?
thanks
Possible Duplicate:
Parsing Dates and Times from Strings using python
I'm reading a string
"2011-06-11"
How can I cast this to a date object?
thanks
If you know it will be in that format, you can use the strptime
function:
datetime.datetime.strptime(s, "%Y-%m-%d").date()
(and it's not a cast, you're actually creating a new date out of the string)
If you don't know the format of the date, I suggest looking at the dateutil module which provides a powerful date parsing function.
In [105]: import datetime as dt
This parses the string and returns a dt.datetime
object:
In [106]: dt.datetime.strptime('2011-06-11',"%Y-%m-%d")
Out[106]: datetime.datetime(2011, 6, 11, 0, 0)
This returns a dt.date
object:
In [108]: dt.datetime.strptime('2011-06-11',"%Y-%m-%d").date()
Out[108]: datetime.date(2011, 6, 11)
The strptime
method is documented here, and the format string "%Y-%m-%d"
is explained here.
Do this:
import datetime
date = datetime.datetime.strptime('2011-06-11', '%Y-%m-%d')
datetime.datetime.strptime("2011-06-11", "%Y-%m-%d")
Also check out How to parse an ISO 8601-formatted date?