**截止文章發布chinese_calendar版本為1.8.0,大約在每年的11月份更新次年的假日新版本
1 2 3 4 5 6 7 8 | import datetime
from chinese_calendar import is_workday
def get_pervious_work_day(day: datetime):
"" "获取上一个工作日" ""
day = day - datetime.timedelta(days=1)
if is_workday(day):
return day
return get_pervious_work_day(day)
|
登入後複製
測試週六日:
1 2 3 | today = datetime. date .today().replace(day=20)
date = get_pervious_work_day(today)
print ( date )
|
登入後複製
測試2023春節:
1 2 3 | today = datetime. date .today().replace(day=28).replace(month=1)
date = get_pervious_work_day(today)
print ( date )
|
登入後複製

#測試2023勞動節:
1 2 3 | today = datetime. date .today().replace(day=4).replace(month=5)
date = get_pervious_work_day(today)
print ( date )
|
登入後複製

#測試2023國慶節:
1 2 3 | today = datetime. date .today().replace(day=7).replace(month=10)
date = get_pervious_work_day(today)
print ( date )
|
登入後複製
擴展:Python計算某個工作日後的日期
剛開始想自己寫,但是因為中國的假日時間並不是固定的,因此需要自己持續並手動填寫日期是否是法定假日,比較麻煩,所以找到python有一個叫chinese_calendar的模組,該作者應該會持續更新
代碼和思路其實都很簡單
我的需求是計算某一日期開始,多少個工作天後這個日期是多少
下面的例子,是我用2021年9月10日到2022年9月10日這一年的時間範圍內
要計算2021年9月10日之後30個工作日,是什麼日期
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import chinese_calendar
import datetime
def after_work_day():
year = 2021
month = 9
day = 10
# after_work_days是设置多少个工作日
after_work_days = 30
next_year = year + 1
range_time = datetime.datetime(next_year, month, day)
# 如果一年后的时间超过了模块规定的最长时间,那么直接取最新版的最大时间 截止目前(2022.11.30)最新版到2022年末,需要等国家出台了明年的放假安排之后可能才会更新
if range_time >= datetime.datetime(2022, 12, 31):
range_time = datetime.datetime(2022, 12, 31)
work_days = chinese_calendar.get_workdays(datetime.datetime(year, month, day), range_time)
count = 0
for work_day in work_days:
count += 1
if count > after_work_days:
print (work_day)
break
if __name__ == '__main__':
after_work_day()
|
登入後複製
有一個需要注意的點就是二月份的天數,閏年和平年的天數不一樣,根據需求考慮進去
以上是python怎麼利用chinese_calendar來取得上一個工作日日期的詳細內容。更多資訊請關注PHP中文網其他相關文章!