I have this string:
'2012-02-10' # (year-month-day)
and I need it to be as date type for me to use the date function isoweekday()
.
Does anyone know how I can convert this string into a date?
This question is related to
python
string
date
type-conversion
While it seems the question was answered per the OP's request, none of the answers give a good way to get a datetime.date
object instead of a datetime.datetime
. So for those searching and finding this thread:
datetime.date
has no .strptime
method; use the one on datetime.datetime
instead and then call .date()
on it to receive the datetime.date
object.
Like so:
>>> from datetime import datetime
>>> datetime.strptime('2014-12-04', '%Y-%m-%d').date()
datetime.date(2014, 12, 4)
Use datetime.datetime.strptime
:
>>> import datetime
>>> date = datetime.datetime.strptime('2012-02-10', '%Y-%m-%d')
>>> date.isoweekday()
5
from datetime import datetime
a = datetime.strptime(f, "%Y-%m-%d")
>>> from datetime import datetime
>>> year, month, day = map(int, my_date.split('-'))
>>> date_object = datetime(year, month, day)
Source: Stackoverflow.com