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)
Answer from Darian Moody on Stack OverflowWhile 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)
You can do that with datetime.strptime()
Example:
>>> from datetime import datetime
>>> datetime.strptime('2012-02-10' , '%Y-%m-%d')
datetime.datetime(2012, 2, 10, 0, 0)
>>> _.isoweekday()
5
You can find the table with all the strptime directive here.
To increment by 2 days if .isweekday() == 6, you can use timedelta():
>>> import datetime
>>> date = datetime.datetime.strptime('2012-02-11' , '%Y-%m-%d')
>>> if date.isoweekday() == 6:
... date += datetime.timedelta(days=2)
...
>>> date
datetime.datetime(2012, 2, 13, 0, 0)
>>> date.strftime('%Y-%m-%d') # if you want a string again
'2012-02-13'
Videos
datetime.strptime parses an input string in the user-specified format into a timezone-naive datetime object:
>>> from datetime import datetime
>>> datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
datetime.datetime(2005, 6, 1, 13, 33)
To obtain a date object using an existing datetime object, convert it using .date():
>>> datetime.strptime('Jun 1 2005', '%b %d %Y').date()
date(2005, 6, 1)
Links:
strptimedocs: Python 2, Python 3strptime/strftimeformat string docs: Python 2, Python 3strftime.org format string cheatsheet
Notes:
strptime= "string parse time"strftime= "string format time"
Use the third-party dateutil library:
from dateutil import parser
parser.parse("Aug 28 1999 12:00AM") # datetime.datetime(1999, 8, 28, 0, 0)
It can handle most date formats and is more convenient than strptime since it usually guesses the correct format. It is also very useful for writing tests, where readability is more important than performance.
Install it with:
pip install python-dateutil