2012-01-12 243 views
0
start_date = '07_Nov_2011' 
end_date = '10_Jan_2012' 

我想打印在同一格式的所有中間日期:如何獲取給定開始日期和結束日期的中間日期?

day_month_year 

如果我能以某種方式轉換起始日期到日期類型我可以這樣做:

sdate+timedelta(1)).strftime('%d_%b_%Y') 

如何轉換它?還是有更好的方法來做到這一點?

回答

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. 
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 
相關問題