我有以下日期类型:
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)
)
}
我想知道新的日期是否是任何假期前一天的劳动节(周一至周五),而且它本身不是假期。
例如,我有以下三个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
对应于指定的规则。
我该怎么做?
答案 0 :(得分:1)
试试这个
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
答案 1 :(得分:1)
您可以使用weekday()
功能获取日期对象的星期几。该函数返回一个从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是任何声明的日期时间对象。您还可以使用additionalnal for循环来迭代日期时间对象列表。
答案 2 :(得分:0)
这是一个快速完成此任务的功能。该功能将使用您的假期字典,并将根据这些假期评估输入日期,并将返回输入日期是周末,假日的1天内还是假日的某一天内的工作日。如果需要,您可以更改函数以返回更多或更少的细节,但这应该符合您描述的需求。
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'
答案 3 :(得分:0)
我这样解决了:
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."