开发者

calculating the next day from a "YYYYMMDD" formatted string

开发者 https://www.devze.com 2023-03-04 21:53 出处:网络
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 nex

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消