我有以下代码来做到这一点,但我如何能做得更好?现在我认为它比嵌套循环更好,但是当您在列表理解中使用生成器时,它开始变得像perl一行程序。
day_count = (end_date - start_date).days + 1
for single_date in [d for d in (start_date + timedelta(n) for n in range(day_count)) if d <= end_date]:
print strftime("%Y-%m-%d", single_date.timetuple())
笔记
我不是用这个来打印的。这只是为了演示。
start_date和end_date变量是datetime。date对象,因为我不需要时间戳。(它们将用于生成报告)。
样例输出
开始日期为2009-05-30,结束日期为2009-06-09:
2009-05-30
2009-05-31
2009-06-01
2009-06-02
2009-06-03
2009-06-04
2009-06-05
2009-06-06
2009-06-07
2009-06-08
2009-06-09
使用dateutil库:
from datetime import date
from dateutil.rrule import rrule, DAILY
a = date(2009, 5, 30)
b = date(2009, 6, 9)
for dt in rrule(DAILY, dtstart=a, until=b):
print dt.strftime("%Y-%m-%d")
这个python库有许多更高级的特性,其中一些非常有用,比如相对增量,并且被实现为单个文件(模块),很容易包含到项目中。
这个函数有一些额外的特性:
can pass a string matching the DATE_FORMAT for start or end and it is converted to a date object
can pass a date object for start or end
error checking in case the end is older than the start
import datetime
from datetime import timedelta
DATE_FORMAT = '%Y/%m/%d'
def daterange(start, end):
def convert(date):
try:
date = datetime.datetime.strptime(date, DATE_FORMAT)
return date.date()
except TypeError:
return date
def get_date(n):
return datetime.datetime.strftime(convert(start) + timedelta(days=n), DATE_FORMAT)
days = (convert(end) - convert(start)).days
if days <= 0:
raise ValueError('The start date must be before the end date.')
for n in range(0, days):
yield get_date(n)
start = '2014/12/1'
end = '2014/12/31'
print list(daterange(start, end))
start_ = datetime.date.today()
end = '2015/12/1'
print list(daterange(start, end))
您可以简单而可靠地使用pandas库在两个日期之间生成一系列日期
import pandas as pd
print pd.date_range(start='1/1/2010', end='1/08/2018', freq='M')
您可以通过设置“freq”为D, M, Q, Y来改变生成日期的频率
(每天,每月,每季,每年
)
你可以使用箭头:
这是一个来自文档的例子,在几个小时内迭代:
from arrow import Arrow
>>> start = datetime(2013, 5, 5, 12, 30)
>>> end = datetime(2013, 5, 5, 17, 15)
>>> for r in Arrow.range('hour', start, end):
... print repr(r)
...
<Arrow [2013-05-05T12:30:00+00:00]>
<Arrow [2013-05-05T13:30:00+00:00]>
<Arrow [2013-05-05T14:30:00+00:00]>
<Arrow [2013-05-05T15:30:00+00:00]>
<Arrow [2013-05-05T16:30:00+00:00]>
要在几天内迭代,你可以这样使用:
>>> start = Arrow(2013, 5, 5)
>>> end = Arrow(2013, 5, 5)
>>> for r in Arrow.range('day', start, end):
... print repr(r)
(没有检查你是否能通过datetime。日期对象,但无论如何箭头对象通常更容易)
import datetime
def daterange(start, stop, step=datetime.timedelta(days=1), inclusive=False):
# inclusive=False to behave like range by default
if step.days > 0:
while start < stop:
yield start
start = start + step
# not +=! don't modify object passed in if it's mutable
# since this function is not restricted to
# only types from datetime module
elif step.days < 0:
while start > stop:
yield start
start = start + step
if inclusive and start == stop:
yield start
# ...
for date in daterange(start_date, end_date, inclusive=True):
print strftime("%Y-%m-%d", date.timetuple())
此函数通过支持负步长等功能,可以实现超出严格要求的功能。只要分解了范围逻辑,就不需要单独的day_count,最重要的是,当从多个地方调用函数时,代码变得更容易阅读。