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

如何结合datetime.timedelta与strftime获取格式化的下周日日期

解决方案

你可以直接对计算出的下周日日期对象调用strftime()方法,不需要额外转换字符串,两种写法都可以:

链式调用写法

import datetime
import time

print((datetime.date.today() + datetime.timedelta(7 - int(time.strftime("%u")))).strftime("%d.%m.%Y"))

拆分变量写法(更易读)

import datetime
import time

next_sunday = datetime.date.today() + datetime.timedelta(7 - int(time.strftime("%u")))
print(next_sunday.strftime("%d.%m.%Y"))

说明

datetime.date.today() + datetime.timedelta(...)返回的是标准的date对象,和datetime.date.today()属于同一类型,因此直接调用它的strftime()方法就能完成格式化,完全不需要先转成字符串再处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 06:35:56