python计算日期之间的放假日期
本文实例为大家分享了python计算日期之间的放假日期,供大家参考,具体内容如下
代码如下:
#encoding=utf-8 print'中国' #自动查询节日给定起始日期和结束日期,自动获取总共的节假日天数 importdatetime fromdateutilimportrrule,easter try:set exceptNameError:fromsetsimportSetasset #复活节 defall_easter(start,end): easters=[easter.easter(y)foryinxrange(start.year,end.year+1)] return[dfordineastersifstart<=d<=end] #开始到结束的节礼日列表 defall_boxing(start,end): one_day=datetime.timedelta(days=1) boxings=[easter.easter(y)+one_dayforyinxrange(start.year,end.year+1)] return[dfordinboxingsifstart<=d<=end] #返回开始和结束日期之间的圣诞节列表 defall_christmas(start,end): christmases=[datetime.date(y,12,25)foryinxrange(start.year,end.year+1)] return[dfordinchristmasesifstart<=d<=end] #返回劳动节列表 defall_labor(start,end): labors=rrule.rrule(rrule.YEARLY,bymonth=9,byweekday=rrule.MO(1),dtstart=start,until=end) return[d.date()fordinlabors] #读取设定的节假日 defread_holidays(start,end,holidays_file='holidays.txt'): try: holidays_file=open(holidays_file) exceptIOError,err: print'openfailed' return[] holidays=[] forlineinholidays_file: ifline.isspace()orline.startswith('#'): continue try: y,m,d=[int(x.strip())forxinline.split(',')] date=datetime.date(y,m,d) exceptValueError: print'Invalidlinefind' continue ifstart<=date<=end: holidays.append(date) holidays_file.close() returnholidays holidays_by_country={ 'US':(all_easter,all_christmas,all_labor), 'IT':(all_easter,all_boxing,all_labor) } defholidays(cc,start,end,holidays_file='holidays.txt'): all_holidays=read_holidays(start,end,holidays_file) functions=holidays_by_country.get(cc,()) forfunctioninfunctions: all_holidays+=function(start,end) all_holidays=list(set(all_holidays)) return(len(all_holidays),all_holidays) test_file=open(r'D:\123.txt','w') test_file.write('2014,3,23') test_file.close() printholidays('US',datetime.date(2014,1,1),datetime.date(2014,12,31),r'D:\123.txt')
打印结果如下:
中国
(4,[datetime.date(2014,4,20),datetime.date(2014,12,25),datetime.date(2014,3,23),datetime.date(2014,9,1)])
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。