确定连续的日期 [英] Determine consecutive dates
问题描述
我有一个 datetime.dates
的列表,我需要检查每个日期是否来自下一个连续月份。
I have a list of datetime.dates
and I need to check if each date is from the next consecutive month.
希望从代码中可以清楚地看出我的意思:
Hope it's clear what do I mean from the code:
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_conecutive
?
很多谢谢您的帮助(建议,提示,代码或任何有帮助的东西)!
Many thanks for any help (advise, hint, code or anything helpful)!
推荐答案
遍历列表中的每个项目(最后一个除外) ,然后将其与下一项进行比较。如果第二个月份的月份比第一个月份的月份大一个正好,或者第二个月份的月份比第一个月份大一个,则第二个项目是连续的。第一次失败时返回 False
,否则最后返回 True
。
Loop through each item of the list except the last, and compare it to the next item. Two items are consecutive if the month of the second is exactly one greater than the month of the first, or if the month of the second is 1 and the year of the second is exactly one greater than the year of the first. Return False
at the first failure, otherwise return True
at the end.
编辑:在第二种情况下,除了第二个月份为1以外,显然第一个月份必须为12。
In the second case, obviously the month of the first must be 12, in addition to the month of the second being 1. Code updated.
编辑2:在第一种情况下,显然年份应该相同。这就是你写得太快的结果。
EDIT 2: And in the first case, obviously the year should be the same. That's what you get for writing too quickly.
F'srinstance:
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)])
另一种实现方式,可能更容易理解,但基本上可以实现事情:
An alternative implementation, possibly easier to follow but basically doing the same thing:
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
这篇关于确定连续的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!