Search code examples
pythonpython-2.7datetimestrptime

How to apply a rule to datetime variables?


I have the following day types:

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

I want to know if the new date is a labour day (Monday-Friday) that is located 1 day before any holiday, and it is not a holiday itself.

For example, I have the following three datetime variables:

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

Only dt2 corresponds to the specified rule.

How can I do this?


Solution

  • I solved it this way:

    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."