如何锚定特定日期计算上周日期并动态生成图表标题?
Got it, let's break this down into actionable steps to get exactly what you need: dynamically calculating the previous Sunday-to-Saturday week range relative to any anchor date, then formatting that range into your chart title in either DD/MM/YYYY or English ordinal format.
1. 核心逻辑:计算已结束的上周(周日至周六)范围
First, we need a reliable way to get the most recently completed Sunday-to-Saturday week, regardless of what the anchor date is. Here's a Python function that handles this correctly:
from datetime import datetime, timedelta def get_last_completed_week(anchor_date=None): # Use current date if no anchor date is provided if not anchor_date: anchor_date = datetime.today() # Calculate the most recent past Saturday weekday = anchor_date.weekday() # Monday=0, Sunday=6 if weekday == 5: # Date is already a Saturday last_saturday = anchor_date elif weekday == 6: # Date is Sunday, so previous Saturday is one day prior last_saturday = anchor_date - timedelta(days=1) else: # Monday to Friday: subtract (weekday + 1) days to reach last Saturday last_saturday = anchor_date - timedelta(days=weekday + 1) # Last Sunday is 6 days before last Saturday last_sunday = last_saturday - timedelta(days=6) return last_sunday, last_saturday
How this works:
- If your anchor date is a Saturday, it returns that Saturday and the corresponding Sunday 6 days prior (the full week just ending)
- If your anchor date is a Sunday, it returns the previous Saturday and its corresponding Sunday (the week that ended the day before)
- If your anchor date is Monday-Friday, it jumps back to the most recent Saturday, then calculates the Sunday that started that week
2. 日期格式转换:支持两种格式
Next, we need functions to format the dates into either DD/MM/YYYY or English ordinal style (e.g., "April 22nd, 2018").
DD/MM/YYYY Format
This is straightforward with Python's strftime:
def format_ddmmyyyy(date): return date.strftime("%d/%m/%Y")
English Ordinal Format
We need a helper to add the correct suffix (st/nd/rd/th) to the day:
def get_ordinal_suffix(day): # Handle special cases for 11-13 if 11 <= day <= 13: return "th" # Handle regular cases last_digit = day % 10 if last_digit == 1: return "st" elif last_digit == 2: return "nd" elif last_digit == 3: return "rd" else: return "th" def format_ordinal(date): day_suffix = get_ordinal_suffix(date.day) return date.strftime(f"%B {date.day}{day_suffix}, %Y")
3. 整合生成图表标题
Now we can combine these functions to generate your desired chart title. Here's an example:
# Example 1: Use current date as anchor last_sun, last_sat = get_last_completed_week() # DD/MM/YYYY title title_ddmmyyyy = f"Conversations ({format_ddmmyyyy(last_sun)}-{format_ddmmyyyy(last_sat)})" print(title_ddmmyyyy) # Output (if today is 2024-05-20, Monday): Conversations (12/05/2024-18/05/2024) # Example 2: Use a specific anchor date (matches your sample) anchor_date = datetime(2018, 4, 29) # Monday, April 29th 2018 last_sun, last_sat = get_last_completed_week(anchor_date) # Ordinal format title title_ordinal = f"Conversations ({format_ordinal(last_sun)}-{format_ordinal(last_sat)})" print(title_ordinal) # Output: Conversations (April 22nd, 2018-April 28th, 2018)
验证正确性
Let's test edge cases to ensure it works:
- Anchor date is Sunday, April 22nd 2018: Returns April 15th (Sunday) to April 21st (Saturday)
- Anchor date is Saturday, April 28th 2018: Returns April 22nd (Sunday) to April 28th (Saturday)
- Anchor date is Wednesday, April 25th 2018: Returns April 15th (Sunday) to April 21st (Saturday)
This ensures you always get the correct completed Sunday-to-Saturday week relative to your anchor date.
内容的提问来源于stack exchange,提问作者Mus

