首页 > 解决方案 > Python 时间算术 - 从 python 日期时间对象中删除 3 小时

问题描述

我正在研究熊猫图,需要从比当前时间早 3 小时开始绘图,以便删除 3 小时前之前的多余数据。

我最终这样做了:

import datetime
todaydate = datetime.datetime.now() # sets todaydate to the current date and time`
tdiff = datetime.timedelta(hours=-3) # sets a time delay object to -3 hours
plotfrom = todaydate + tdiff # adds the datetime object to the timedelta object.

print (plotfrom.strftime("%Y-%m-%d %H:%M:%S") + " is three hours earlier than " + todaydate.strftime("%Y-%m-%d %H:%M:%S")  )

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

我的问题是是否有一种“单线”方式可以在不使用 diff 变量的情况下做同样的事情?

标签: pythondatetime

解决方案


我喜欢这样arrow的东西,因为语法真的很容易记住。

todaydate = arrow.now()
plotform = todaydate.shift(hours=-3)

print(plotfrom.format("YYYY-MM-DD HH:mm:ss") + " is three hours earlier than " + todaydate.format("YYYY-MM-DD HH:mm:ss"))

要从中获取原始datetime对象,只需plotform.datetime.


推荐阅读