如何在Python中检测日期是否连续?

2024-05-13 22:32:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有“日期”字段的访问表。每个记录都有随机日期。我已经构建了一个脚本,将所有记录追加到一个列表中,然后设置该列表以仅筛选出唯一值:

dateList = []
# cursor search through each record and append all records in the date 
# field to a python list
for row in rows:
   dateList.append(row.getValue("DATE_OBSERVATION").strftime('%m-%d-%Y'))

# Filter unique values to a set
newList = list(set(dateList))

这将返回(在我的测试表上):

['07-06-2010'、'06-24-2010'、'07-05-2010'、'06-25-2010']

现在我有了“DATE_OBSERVATION”字段的唯一值,我想检测是否:

  • 日期是单一的(即只返回一个唯一的日期,因为这是每个记录中的日期)
  • 如果日期是一个日期范围(即所有日期都属于连续范围)
  • 如果日期是多个日期,但不在连续日期范围内

任何建议都将不胜感激! 迈克


Tags: toin脚本列表searchdate记录cursor
3条回答

另一个版本使用了和我的另一个答案相同的逻辑。

from datetime import date, timedelta

# Definition 1: 1/1/14, 1/2/14, 1/2/14, 1/3/14 is consider consecutive
# Definition 2: 1/1/14, 1/2/14, 1/2/14, 1/3/14 is consider not consecutive

# datelist = [date(2014, 1, 1), date(2014, 1, 3),
#             date(2013, 12, 31), date(2013, 12, 30)]

# datelist = [date(2014, 2, 19), date(2014, 2, 19), date(2014, 2, 20),
#             date(2014, 2, 21), date(2014, 2, 22)]

datelist = [date(2014, 2, 19), date(2014, 2, 21),
            date(2014, 2, 22), date(2014, 2, 20)]

datelist.sort()

previousdate = datelist[0]

for i in range(1, len(datelist)):
    #if (datelist[i] - previousdate).days == 1 or (datelist[i] - previousdate).days == 0:  # for Definition 1
    if (datelist[i] - previousdate).days == 1:    # for Definition 2
        previousdate = datelist[i]
    else:
        previousdate = previousdate + timedelta(days=-1)

if datelist[-1] == previousdate:
    print "dates are consecutive"
else:
    print "dates are not consecutive"

与其滚动自己的consecutive函数,不如使用datetime对象的.toordinal()方法将日期对象转换为整数。序数日期集的最大值和最小值之间的差大于该集的长度一:

from datetime import datetime

date_strs = ['07-06-2010', '06-24-2010', '07-05-2010', '06-25-2010']
# date_strs = ['02-29-2012', '02-28-2012', '03-01-2012']
# date_strs = ['01-01-2000']
dates = [datetime.strptime(d, "%m-%d-%Y") for d in date_strs]

date_ints = set([d.toordinal() for d in dates])

if len(date_ints) == 1:
    print "unique"
elif max(date_ints) - min(date_ints) == len(date_ints) - 1:
    print "consecutive"
else:
    print "not consecutive"

使用数据库按升序选择唯一日期:

  • 如果查询返回单个日期,则这是您的第一个案例

  • 否则,请查明日期是否连续:

    import datetime
    
    def consecutive(a, b, step=datetime.timedelta(days=1)):
        return (a + step) == b
    

代码布局:

dates = <query database>
if all(consecutive(dates[i], dates[i+1]) for i in xrange(len(dates) - 1)):
   if len(dates) == 1: # unique
      # 1st case: all records have the same date
   else:
      # the dates are a range of dates
else:
   # non-consecutive dates

相关问题 更多 >