如何将规则应用于日期时间变量?

How to apply a rule to datetime variables?

我有以下日期类型:

daytypes = {
    'Holidays_1': (
        date(2017, 4, 20),
        date(2017, 7, 10)
    ),
    'Holidays_2': (
        date(2017, 2, 5),
        date(2017, 5, 12),
        date(2017, 12, 14)
    )
}

我想知道新日期是否是位于任何假期前 1 天的劳动节(周一至周五),并且它本身不是假期。

例如,我有以下三个datetime变量:

from datetime import datetime
dt1 = datetime.strptime("2017-02-04 11:12:20.0", "%Y-%m-%d %H:%M:%S.%f")
dt2 = datetime.strptime("2017-05-11 20:00:00.0", "%Y-%m-%d %H:%M:%S.%f")
dt3 = datetime.strptime("2017-02-06 12:00:00.0", "%Y-%m-%d %H:%M:%S.%f")

只有dt2符合指定的规则。

我该怎么做?

试试这个

from datetime import datetime as date
from datetime import timedelta, datetime

daytypes = {
    'Holidays_1': (
        date(2017, 4, 20),
        date(2017, 7, 10)
    ),
    'Holidays_2': (
        date(2017, 2, 5),
        date(2017, 5, 12),
        date(2017, 12, 14)
    )
}

holidays = []
for d in daytypes:
    holidays.extend(daytypes[d])

dt2 = datetime.strptime("2017-05-11 20:00:00.0", "%Y-%m-%d %H:%M:%S.%f")

for h in holidays:
    if h-dt2 < timedelta(1) and h-dt2 > timedelta(0):
        return True

这里有一个快速函数可以完成此操作。该函数采用您的假期字典,并将根据这些假期评估输入日期,并将 return 输入日期是周末、假期的 1 天内,还是不在假期的一天内的工作日。如果需要,您可以将功能更改为 return 或多或少的细节,但这应该符合您描述的需求。

def check_holidays(holidays, input_date):
    if input_date.weekday() >= 5:
        return 'Is a weekend date'
    for holiday, holiday_dates in holidays.items():
        holiday_range = []
        for h_date in holiday_dates:
            holiday_range.append(h_date)
            holiday_range.append(h_date - timedelta(days=1))
        if input_date.date() in holiday_range:
            return 'Date is within 1 day of a holiday'
    return 'Date is a weekday and not within 1 day of a holiday'

您可以使用 weekday() 函数来获取您的日期对象是星期几。函数returns一个从0(星期一)到6(星期日)的整数。

例如:

>>> from datetime import datetime, date
>>> dt1 = datetime.strptime("2017-02-04 11:12:20.0", "%Y-%m-%d %H:%M:%S.%f")
>>> holiday1 = date(2017, 02, 05)
>>> # Is the holiday one day ahead of the date?
>>> print date(dt1.year, dt1.month, dt1.day + 1) == holiday1 
True
>>> # Is the date a weekday?
>>> print dt1.weekday() in range(0,4) # Days from 0 to 4 are working days
False

文档在这里:https://docs.python.org/2/library/datetime.html#datetime.date.weekday

编辑:您可以使用 for 循环遍历每个假期:

for holiday_tuple in daytypes.keys():
    for holiday in holiday_tuple:
        # Do whatever you need here
        print date(dtx.year, dtx.month, dtx.day + 1) == holiday

其中 dtx 是任何已声明的日期时间对象。您还可以使用附加的 for 循环来遍历日期时间对象列表。

我是这样解决的:

holidays = []
for d in daytypes:
    holidays.extend(daytypes[d])

if (dt.isoweekday() >= 1 and dt.isoweekday() <= 5 and date(dt.year, dt.month, dt.day + 1) in holidays):
    print "Date is within 1 day of a holiday."
else:
    print "Date is a weekday and not within 1 day of a holiday."