如何在Python中检测日期是否连续? [英] How to detect if dates are consecutive in Python?

查看:922
本文介绍了如何在Python中检测日期是否连续?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有日期字段的访问表。每个记录都有随机日期。我构建了一个脚本,将所有记录追加到列表中,然后将列表设置为仅过滤唯一值:

I have an access table with a 'Date' field. it has random dates for each record. I've built a script to append all the records into a list and then set the list to filter out only the unique values:

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))

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

This returns (on my test table):

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

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

现在,对于 DATE_OBSERVATION字段,我具有唯一的值,我想检测是否:

Now that I have the unique values for the "DATE_OBSERVATION" field, I want to detect if:


  • 日期是单个(即仅返回一个唯一的日期,因为它是每个记录中的日期)

  • 如果日期是一个日期范围(即所有日期都属于连续范围)

  • 如果日期是多个日期,但不在以下范围内连续的日期

任何建议将不胜感激!
Mike

Any suggestions would be much appreciated! Mike

推荐答案

而不是滚动自己的连续函数您可以使用datetime对象的 .toordinal()方法将日期对象简单地转换为整数。序数日期集的最大值和最小值之差比该日期集的长度大一倍。

Rather than rolling your own consecutive function you can simply convert date objects to integers using the .toordinal() method of datetime objects. The difference between the maximum and minimum value of the set of ordinal dates is one more than the length of the set:

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"

这篇关于如何在Python中检测日期是否连续?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆