[英]How to get the intermediate dates given the start date and end date?
start_date = '07_Nov_2011'
end_date = '10_Jan_2012'
I want to print all the intermediate dates in the same format: 我想以相同格式打印所有中间日期:
day_month_year
If I can somehow convert start_date to date type I can do this: 如果我可以将start_date转换为日期类型,则可以执行以下操作:
sdate+timedelta(1)).strftime('%d_%b_%Y')
How do I convert it? 如何转换? Or is there a better way to do this? 还是有更好的方法来做到这一点?
You can use datetime.datetime.strptime(...)
to do the conversion. 您可以使用datetime.datetime.strptime(...)
进行转换。 Like this: 像这样:
>>> datetime.datetime.strptime('07_Nov_2011', '%d_%b_%Y').date()
datetime.date(2011, 11, 7)
You can print all the intermediate dates with something like this: 您可以使用以下方式打印所有中间日期:
>>> start_date = '07_Nov_2011'
>>> end_date = '10_Jan_2012'
>>>
>>> first = datetime.datetime.strptime(start_date, '%d_%b_%Y')
>>> last = datetime.datetime.strptime(end_date, '%d_%b_%Y')
>>> for i in xrange((last-first).days):
... print (first+datetime.timedelta(i)).strftime('%d_%b_%Y')
...
07_Nov_2011
08_Nov_2011
09_Nov_2011
10_Nov_2011
11_Nov_2011
etc.
You can parse the dates like so: 您可以像这样解析日期:
import datetime
start_date = '07_Nov_2007'
end_date = '10_Nov_2007'
startDate = datetime.datetime.strptime(start_date, '%d_%b_%Y')
endDate = datetime.datetime.strptime(end_date, '%d_%b_%Y')
oneDay = datetime.timedelta(days = 1)
currentDate = startDate
while currentDate <= endDate:
print currentDate
currentDate += oneDay
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.