python如何生成一個日期列表?
比如輸入起止日期就能生成這段日期的一個列表def datelist(8,3,10,9) return L=[8月3日,8月4日,...,10月9日]
建議用pandas庫:
import pandas as pd
from datetime import datetime
def datelist(beginDate, endDate):
# beginDate, endDate是形如『20160601』的字元串或datetime格式
date_l=[datetime.strftime(x,%Y-%m-%d) for x in list(pd.date_range(start=beginDate, end=endDate))]
return date_l
import datetime
def datelist(start, end):
start_date = datetime.date(*start)
end_date = datetime.date(*end)
result = []
curr_date = start_date
while curr_date != end_date:
result.append("%04d%02d%02d" % (curr_date.year, curr_date.month, curr_date.day))
curr_date += datetime.timedelta(1)
result.append("%04d%02d%02d" % (curr_date.year, curr_date.month, curr_date.day))
return result
if __name__ == "__main__":
print datelist((2014, 7, 28), (2014, 8, 3))
import datetime
def dateRange(start, end, step=1, format="%Y-%m-%d"):
strptime, strftime = datetime.datetime.strptime, datetime.datetime.strftime
days = (strptime(end, format) - strptime(start, format)).days
return [strftime(strptime(start, format) + datetime.timedelta(i), format) for i in xrange(0, days, step)]
if __name__ == __main__:
print dateRange("2017-01-01", "2017-01-03")
# ["2017-01-01", "2017-01-02"]
import time
def dateRange(bgn, end):
fmt = %Y-%m-%d
bgn = int(time.mktime(time.strptime(bgn,fmt)))
end = int(time.mktime(time.strptime(end,fmt)))
return [time.strftime(fmt,time.localtime(i)) for i in range(bgn,end+1,3600*24)]
推薦閱讀:
※黃哥Python細說,學到什麼程度可以找到工作?
※python與numpy使用的一些小tips(5)
※一道入群驗證的Python題
※為什麼國內微博都是php開發的呢?
※python中的漢諾塔遞歸演算法的具體運算過程是怎樣的?
TAG:Python |