在Python中查找任意给定年份的6月和12月的最后营业日期,通常需要考虑周末和可能的公共假期。以下是一个示例代码,它使用了pandas
库来处理日期,并假设周末(周六和周日)不是营业日,同时考虑了公共假期。
pandas
库中的date_range
函数来生成日期序列。import pandas as pd
from datetime import datetime
def get_last_business_day(year):
# 假设的公共假期列表(示例)
holidays = [
datetime(year, 1, 1), # 元旦
datetime(year, 12, 25), # 圣诞节
# 添加其他公共假期...
]
# 定义一个函数来检查是否是营业日
def is_business_day(date):
return date.weekday() < 5 and date not in holidays
# 查找6月和12月的最后营业日期
last_business_day_june = None
last_business_day_december = None
for month in [6, 12]:
# 生成该月的所有日期
dates_in_month = pd.date_range(start=f"{year}-{month}-01", end=f"{year}-{month+1}-01", closed='left')
for date in reversed(dates_in_month):
if is_business_day(date):
if month == 6:
last_business_day_june = date
elif month == 12:
last_business_day_december = date
break
return last_business_day_june, last_business_day_december
# 示例使用
year = 2023
june_last_business_day, december_last_business_day = get_last_business_day(year)
print(f"2023年6月的最后营业日期是: {june_last_business_day}")
print(f"2023年12月的最后营业日期是: {december_last_business_day}")
pandas
库进行高效的日期操作。is_business_day
函数来处理特定的营业日规则。pytz
库来管理时区。通过上述方法和代码示例,可以有效地找到任意给定年份的6月和12月的最后营业日期。
领取专属 10元无门槛券
手把手带您无忧上云