start_date = '07_Nov_2011'
end_date = '10_Jan_2012'
我想以相同的格式打印所有中间日期:
day_month_year
如果我能以某种方式将start_date转换为日期类型,我可以这样做:
sdate+timedelta(1)).strftime('%d_%b_%Y')
如何转换它?或者有更好的方法吗?
答案 0 :(得分:4)
您可以使用datetime.datetime.strptime(...)
进行转换。像这样:
>>> datetime.datetime.strptime('07_Nov_2011', '%d_%b_%Y').date()
datetime.date(2011, 11, 7)
您可以使用以下内容打印所有中间日期:
>>> 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.
答案 1 :(得分:2)
您可以像这样解析日期:
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