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

Python时间运算:如何用单行代码从datetime对象中减去3小时

单行代码实现Pandas绘图起始时间设为当前时间3小时前?

当然可以!你完全不需要额外定义tdiff这个中间变量,直接把时间差的计算逻辑和当前时间的获取合并到一行里就行,代码会更简洁利落。

单行实现方案

import datetime

# 直接将当前时间与-3小时的时间差相加,一步得到目标时间
plotfrom = datetime.datetime.now() + datetime.timedelta(hours=-3)
# 用f-string格式化输出,比字符串拼接更清爽
print(f"{plotfrom.strftime('%Y-%m-%d %H:%M:%S')} is three hours earlier than {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

额外小优化

其实还有个更符合直觉的写法——用减法替代负数加法,读起来更通顺:

plotfrom = datetime.datetime.now() - datetime.timedelta(hours=3)

两种写法的效果完全一致,选你觉得更易读的就好。

运行后你会得到和之前完全相同的输出示例:

2021-07-09 12:58:46 is three hours earlier than 2021-07-09 15:58:46

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 21:17:35