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

转换日期为API指定格式并获取7天前日期时遇报错求助

日期计算与API格式转换问题解决

需求

  • 将日期转换为API要求的格式:YYYY-MM-DD%20HH:NN:SS
  • 获取当前日期7天前的日期

你尝试的代码

from datetime import datetime, timedelta    

end = datetime.now().strftime("%Y-%m-%d%%20%H:%M:%S")
start = end - timedelta(days=7)
print("Start: ", start )
print("End: ", end )

报错信息

unsupported operand type(s) for -: 'str' and 'datetime.timedelta'

问题原因

strftime()方法会把datetime对象转换成字符串类型,而字符串不能和timedelta(时间差对象)进行减法运算——你得先对可运算的datetime对象完成时间差计算,再做格式转换。

修正后的代码

from datetime import datetime, timedelta    

# 先获取当前时间的datetime对象,计算7天前的时间对象
current_time = datetime.now()
start_time = current_time - timedelta(days=7)

# 再将两个时间对象格式化为API需要的字符串格式
end = current_time.strftime("%Y-%m-%d%%20%H:%M:%S")
start = start_time.strftime("%Y-%m-%d%%20%H:%M:%S")

print("Start: ", start )
print("End: ", end )

代码说明

  1. 先保留datetime类型的时间对象:current_time是当前时间的原生datetime对象,支持和timedelta做运算
  2. 计算7天前的时间:start_time = current_time - timedelta(days=7)得到7天前的datetime对象
  3. 最后统一格式化:对两个datetime对象调用strftime(),用%%20转义生成%20(因为strftime中%是特殊占位符,需要双重转义)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:25:31