我有以下代码来执行此操作,但我怎样才能做得更好?现在我认为它比嵌套循环更好,但是当你在列表理解中有一个生成器时,它开始得到Perl-one-liner.
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())
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud) 我需要能够准确地找到python中两个日期之间的月份.我有一个解决方案,但它不是很好(如优雅)或快速.
dateRange = [datetime.strptime(dateRanges[0], "%Y-%m-%d"), datetime.strptime(dateRanges[1], "%Y-%m-%d")]
months = []
tmpTime = dateRange[0]
oneWeek = timedelta(weeks=1)
tmpTime = tmpTime.replace(day=1)
dateRange[0] = tmpTime
dateRange[1] = dateRange[1].replace(day=1)
lastMonth = tmpTime.month
months.append(tmpTime)
while tmpTime < dateRange[1]:
if lastMonth != 12:
while tmpTime.month <= lastMonth:
tmpTime += oneWeek
tmpTime = tmpTime.replace(day=1)
months.append(tmpTime)
lastMonth = tmpTime.month
else:
while tmpTime.month >= lastMonth:
tmpTime += oneWeek
tmpTime = tmpTime.replace(day=1)
months.append(tmpTime)
lastMonth = tmpTime.month
Run Code Online (Sandbox Code Playgroud)
所以只是为了解释一下,我在这里做的是将两个日期转换为iso格式转换为python datetime对象.然后我循环通过在开始日期时间对象中添加一周,并检查月份的数值是否更大(除非月份是12月,然后检查日期是否更少),如果值更大,我将其附加到列表几个月,并一直循环,直到我到达我的结束日期.
它完美地工作它似乎不是一个好方法...
如何在数天,数小时,数周或数月后迭代一次?
就像是:
for date in foo(from_date, to_date, delta=HOURS):
print date
Run Code Online (Sandbox Code Playgroud)
其中foo是一个函数,返回一个迭代器.我一直在查看日历模块,但这只适用于特定年份或月份,而不是日期之间.
我有一个有序(即排序)列表,其中包含按升序排序的日期(作为日期时间对象).
我想编写一个迭代这个列表的函数,并生成每个月的第一个可用日期的另一个列表.
例如,假设我的排序列表包含以下数据:
A = [
'2001/01/01',
'2001/01/03',
'2001/01/05',
'2001/02/04',
'2001/02/05',
'2001/03/01',
'2001/03/02',
'2001/04/10',
'2001/04/11',
'2001/04/15',
'2001/05/07',
'2001/05/12',
'2001/07/01',
'2001/07/10',
'2002/03/01',
'2002/04/01',
]
Run Code Online (Sandbox Code Playgroud)
返回的列表将是
B = [
'2001/01/01',
'2001/02/04',
'2001/03/01',
'2001/04/10',
'2001/05/07',
'2001/07/01',
'2002/03/01',
'2002/04/01',
]
Run Code Online (Sandbox Code Playgroud)
我建议的逻辑是这样的:
def extract_month_first_dates(input_list, start_date, end_date):
#note: start_date and end_date DEFINITELY exist in the passed in list
prev_dates, output = [],[] # <- is this even legal?
for (curr_date in input_list):
if ((curr_date < start_date) or (curr_date > end_date)):
continue
curr_month = curr_date.date.month
curr_year = …Run Code Online (Sandbox Code Playgroud)