python连续输出日期_如何在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']

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

the dates are single (i.e. only one unique date is returned because that is the date in every record)

if the dates are a range of dates (i.e. all of the dates fall into a consecutive range)

if the dates are multiple dates, but are not in a range of consecutive dates

Any suggestions would be much appreciated!

Mike

解决方案

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"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值