您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關python中怎么計算放假日期,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
代碼如下:
#encoding=utf-8 print '中國' #自動查詢節日 給定起始日期和結束日期,自動獲取總共的節假日天數 import datetime from dateutil import rrule,easter try: set except NameError: from sets import Set as set #復活節 def all_easter(start, end): easters = [easter.easter(y) for y in xrange(start.year,end.year+1)] return [d for d in easters if start<=d<=end] #開始到結束的節禮日列表 def all_boxing(start, end): one_day = datetime.timedelta(days=1) boxings = [easter.easter(y) + one_day for y in xrange(start.year,end.year+1)] return [d for d in boxings if start<=d<=end] #返回開始和結束日期之間的圣誕節列表 def all_christmas(start, end): christmases = [datetime.date(y,12,25) for y in xrange(start.year, end.year + 1)] return [d for d in christmases if start<=d<=end] #返回勞動節列表 def all_labor(start, end): labors = rrule.rrule(rrule.YEARLY, bymonth=9, byweekday=rrule.MO(1),dtstart=start, until=end) return [d.date() for d in labors] #讀取設定的節假日 def read_holidays(start, end, holidays_file='holidays.txt'): try: holidays_file = open(holidays_file) except IOError,err: print 'open failed' return [] holidays = [] for line in holidays_file: if line.isspace() or line.startswith('#'): continue try: y,m,d = [int(x.strip()) for x in line.split(',')] date = datetime.date(y,m,d) except ValueError: print 'Invalid line find' continue if start <= date <=end: holidays.append(date) holidays_file.close() return holidays holidays_by_country = { 'US':(all_easter,all_christmas,all_labor), 'IT':(all_easter,all_boxing,all_labor) } def holidays(cc,start,end,holidays_file='holidays.txt'): all_holidays= read_holidays(start,end,holidays_file) functions = holidays_by_country.get(cc,()) for function in functions: 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() print holidays('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)])
關于python中怎么計算放假日期就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。