How can I calculate the next day from a string like 20110531 in the same YYYYMMDD format? In this particular case, I li开发者_开发技巧ke to have 20110601 as the result. Calculating "tomorrow" or next day in static way is not that tough, like this:
>>> from datetime import date, timedelta
>>> (date.today() + timedelta(1)).strftime('%Y%m%d')
'20110512'
>>>
>>> (date(2011,05,31) + timedelta(1)).strftime('%Y%m%d')
'20110601'
But how can I use a string like dt = "20110531"
to get the same result as above?
Here is an example of how to do it:
import time
from datetime import date, timedelta
t=time.strptime('20110531','%Y%m%d')
newdate=date(t.tm_year,t.tm_mon,t.tm_mday)+timedelta(1)
print newdate.strftime('%Y%m%d')
>>> from datetime import datetime
>>> print datetime.strptime('20110531', '%Y%m%d')
2011-05-31 00:00:00
And then do math on that date object as you show in your question.
The datetime library docs.
You are most of the way there! along with the strftime
function which converts a date to a formatted string, there is also a strptime
function which converts back the other way.
To solve your problem you can just replace date.today()
with strptime(yourDateString, '%Y%m%d')
.
ED: and of course you will also have to add strptime
to the end of your from datetime import
line.
精彩评论