Python如何获取上月完整自然月的起止日期?
获取上月完整财务数据日期区间的Python实现
标准库实现方案
Python的datetime标准库就能搞定这个需求,不需要额外依赖。核心逻辑是通过当前日期推导上月的首尾日期:
- 先获取当前月份的第一天,往前推1天得到上月的最后一天
- 再将上月最后一天的日期替换为1,得到上月的第一天
修改后的代码实现
from datetime import datetime, timedelta import pytz from django.conf import settings # 适配你的项目环境,非Django可替换为对应时区配置 def get_last_month_interval() -> tuple: tz = pytz.timezone(settings.TIME_ZONE) now = datetime.now(tz) # 计算当前月第一天,再往前推一天得到上月最后一天 first_day_current = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0) last_day_last_month = first_day_current - timedelta(days=1) # 计算上月第一天 first_day_last_month = last_day_last_month.replace(day=1) return first_day_last_month, last_day_last_month # 生成符合要求的日期字符串 last_month_start, last_month_end = get_last_month_interval() date_from_str = last_month_start.strftime("%Y-%m-%d") date_to_str = last_month_end.strftime("%Y-%m-%d") # 调用财务数据函数 get_sold_products(date_from=date_from_str, date_to=date_to_str)
关键细节说明
- 时区一致性:全程使用业务指定时区生成日期,避免因时区偏移导致的日期错误
- 自动适配月末:不管是28天的平年2月,还是31天的大月,都能自动计算正确的首尾日期,无需额外判断闰年或月份天数
- 时间精度控制:将时间部分重置为00:00:00,确保获取的是完整自然日的区间
内容的提问来源于stack exchange,提问作者Iren E
相关产品推荐
相关产品推荐

