我有datetime.dates
的列表,我需要检查每个日期是否来自下个月。
希望很清楚我的代码是什么意思:
import datetime
from unittest import TestCase
def is_consecutive(dates):
# TODO
return
class DatesTestCase(TestCase):
def test_consecutive(self):
self.assertTrue(is_consecutive([datetime.date(2010, 10, 3),
datetime.date(2010, 11, 8),
datetime.date(2010, 12, 1),
datetime.date(2011, 01, 11)]))
def test_not_consecutive(self):
self.assertFalse(is_consecutive([datetime.date(2010, 7, 6),
datetime.date(2010, 8, 24),
datetime.date(2010, 3, 5),
datetime.date(2010, 10, 25)]))
self.assertFalse(is_consecutive([datetime.date(2010, 10, 6),
datetime.date(2010, 11, 2),
datetime.date(2010, 12, 9),
datetime.date(2010, 01, 20)]))
您将如何实施is_consecutive
?
非常感谢任何帮助(建议,提示,代码或任何有用的帮助)!
答案 0 :(得分:2)
遍历列表中除最后一项之外的每个项目,并将其与下一项目进行比较。如果第二个月的月份恰好比第一个月的月份大一个,或者如果第二个月的月份是1而第二个月的年份恰好大于第一个月的年份,则两个项目是连续的。在第一次失败时返回False
,否则在最后返回True
。
编辑:在第二种情况下,显然第一个月必须是12,除了第二个月是1.代码更新。
编辑2:在第一种情况下,显然年份应该是相同的。这就是你写得太快的原因。
F'rinstance:
#!/usr/bin/python
from datetime import date
def is_consecutive(datelist):
for idx, my_date in enumerate(datelist[:-1]):
if ((datelist[idx + 1].month - my_date.month == 1 and
datelist[idx + 1].year == my_date.year) or
(datelist[idx + 1].month == 1 and
my_date.month == 12 and
datelist[idx + 1].year - my_date.year == 1)):
continue
else:
return False
return True
print is_consecutive([date(2010, 10, 3),
date(2010, 11, 8),
date(2010, 12, 1),
date(2011, 1, 11)])
print is_consecutive([date(2010, 7, 6),
date(2010, 8, 24),
date(2010, 3, 5),
date(2010, 10, 25)])
另一种实现方式,可能更容易遵循,但基本上做同样的事情:
def is_consecutive(datelist):
for idx, my_date in enumerate(datelist[:-1]):
month_diff = datelist[idx + 1].month - my_date.month
year_diff = datelist[idx + 1].year - my_date.year
if ((month_diff == 1 and year_diff == 0) or
(month_diff == -11 and year_diff == 1)):
continue
else:
return False
return True
答案 1 :(得分:2)
这适用于您的示例,并且通常应该正常工作:
def is_consecutive(data):
dates=data[:]
while len(dates)>1:
d2=dates.pop().replace(day=1)
d1=dates[-1].replace(day=1)
d3=d1+datetime.timedelta(days=32)
if d3.month!=d2.month or d3.year!=d2.year:
return False
return True
答案 2 :(得分:1)
以下是此问题的另一种解决方案:
def is_consecutive(dates):
months = [date.month for date in sorted(dates)] # extracting months from date, dates list has to be sorted first
months_diff = [abs(x - months[i - 1]) for i, x in enumerate(months) if i>0] # creates a resulting list of values after subtracting month with a previous month (absolute value is needed to account for the case when subtracting December(12) from January(1)
if not(set(months_diff) - set([1,11])): # if months_diff contains any values other than 11 and 1 then dates are not consecutive
return True
return False