Python新增年度剩余节假日推送功能技术咨询
Hey there! Great job getting the 3-week holiday reminder up and running—adding the "remaining holidays this year" feature is totally doable, let's break it down step by step.
实现思路 & 具体步骤
First, let's align on how your calendar.txt works (I assume each line follows the format YYYY/MM/DD Holiday Name). Here's what we need to do:
1. Create a function to fetch all remaining holidays this year
We need to read your holiday file, then filter out holidays that meet two criteria:
- They fall within the current year
- They haven't happened yet (i.e., are after today)
Here's a reusable function for that:
def get_remaining_holidays(): current_year = datetime.date.today().year today = datetime.date.today() remaining_holidays = [] # Use `with open()` to auto-close the file (safer than manual open/close) with open(holidayFile, 'r') as file: for line in file: line = line.strip() if not line: continue # Skip empty lines to avoid errors # Split date string and holiday name date_str, *name_parts = line.split() holiday_name = ' '.join(name_parts) # Convert string date to a proper date object (with error handling) try: holiday_date = datetime.datetime.strptime(date_str, '%Y/%m/%d').date() except ValueError: print(f"Skipping invalid date format: {date_str}") continue # Check if the holiday is in this year and hasn't happened yet if holiday_date.year == current_year and holiday_date > today: remaining_holidays.append( (holiday_date, holiday_name) ) # Sort holidays by date so they show up in chronological order remaining_holidays.sort(key=lambda x: x[0]) return remaining_holidays
2. Update your reminder function to include both alerts
Now we'll modify your checkTodaysHolidays() to:
- Keep checking for the 3-week-out holiday (your original feature)
- Fetch the full list of remaining holidays
- Combine both into a single, easy-to-read message for your email
Here's the updated function:
def checkTodaysHolidays(): today = datetime.date.today() three_weeks_later = today + datetime.timedelta(days=21) upcoming_3week_holiday = None # Find the holiday 3 weeks from now (cleaned-up version of your original logic) with open(holidayFile, 'r') as file: for line in file: line = line.strip() if not line: continue date_str, *name_parts = line.split() try: holiday_date = datetime.datetime.strptime(date_str, '%Y/%m/%d').date() except ValueError: continue if holiday_date == three_weeks_later: upcoming_3week_holiday = ' '.join(name_parts) break # Get all remaining holidays this year remaining_holidays = get_remaining_holidays() # Build the final message content message = "" # Add 3-week reminder section if upcoming_3week_holiday: message += f"⚠️ 3周后即将到来的节假日:\n{three_weeks_later.strftime('%Y/%m/%d')} - {upcoming_3week_holiday}\n\n" else: message += "⚠️ 3周后没有即将到来的节假日\n\n" # Add remaining holidays section message += "📅 本年度剩余所有节假日:\n" if remaining_holidays: for date, name in remaining_holidays: message += f"{date.strftime('%Y/%m/%d')} - {name}\n" else: message += "本年度已无剩余节假日\n" # Replace this print with your existing email sending code print(message) # Example: send_email(subject="节假日提醒", content=message)
3. Quick Tips to Polish Your Code
- Stick with
with open(): It automatically closes the file, so you don't have to worry about forgettingfile.close()and causing issues - Keep error handling: The
try/exceptblocks catch bad date formats in yourcalendar.txt, so your program won't crash unexpectedly - Sort your lists: Users will appreciate seeing upcoming holidays in chronological order instead of random order
- Modularize email logic: If you haven't already, move your email sending code into a separate
send_email()function—it makes your code easier to read and update later
内容的提问来源于stack exchange,提问作者vbabeginnercs
相关产品推荐
相关产品推荐

