我有一个清单,datetime.dates我需要检查每个日期是否都来自下一个连续月份。希望很清楚我的代码是什么意思:import datetimefrom unittest import TestCasedef is_consecutive(dates): # TODO returnclass 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?
3 回答
慕哥9229398
TA贡献1877条经验 获得超6个赞
这适用于您的示例,并且应该可以正常工作:
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
添加回答
举报
0/150
提交
取消