You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python获取上月连续7天日期列表并格式化及优化代码

Hey ritz! Let's fix up your code to get the string format you want, and make it cleaner and more efficient at the same time.

First: Converting datetime.date to your desired string format

The output you're seeing are datetime.date objects—great for date math, but to get the YYYY-M-D format you want, you have two solid options:

  • Use an f-string for cross-platform consistency (no OS-dependent quirks):
    f"{date_obj.year}-{date_obj.month}-{date_obj.day}"
    
  • Or use strftime() (note: non-padded numbers might need platform-specific specifiers like %-m on Linux/macOS):
    date_obj.strftime("%Y-%-m-%-d")  # Outputs "2019-4-8" instead of "2019-04-08"
    

Second: A cleaner, more efficient version of your code

Your original code calls date.today() multiple times (unnecessary!) and uses a loop with append()—we can streamline this with list comprehensions and handle edge cases like month-end dates better.

Here's the optimized code:

from datetime import date, timedelta

# Store today's date once to avoid redundant calls
today = date.today()

# Calculate the starting point: yesterday's date, shifted to the previous month
yesterday = today - timedelta(days=1)
try:
    start_date = yesterday.replace(month=yesterday.month - 1)
except ValueError:
    # Handle cases where the previous month doesn't have the same day (e.g., March 31 → Feb 31 doesn't exist)
    # Fall back to the last day of the previous month
    start_date = date(yesterday.year, yesterday.month, 1) - timedelta(days=1)

# Generate 7 consecutive dates and format them in one go
formatted_dates = [
    f"{d.year}-{d.month}-{d.day}" 
    for d in [start_date - timedelta(days=i) for i in range(7)]
]

print(formatted_dates)

What this does:

  1. Reduces redundant calls: We only fetch today's date once, which is more efficient.
  2. Handles edge cases: The try/except block fixes errors when the previous month has fewer days than the current one (like March 31 → February 28/29).
  3. Concise generation: Uses list comprehensions to create and format dates in readable, efficient code.
  4. Matches your example: When run on 2019-5-9, it outputs exactly the list you want:
    ['2019-4-8', '2019-4-7', '2019-4-6', '2019-4-5', '2019-4-4', '2019-4-3', '2019-4-2']
    

If you don't need to handle edge cases (e.g., you're sure the date will always exist in the previous month), you can simplify the start_date line to just:

start_date = yesterday.replace(month=yesterday.month - 1)

内容的提问来源于stack exchange,提问作者ritz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:23:40