从python datetime对象中删除3小时

lx0bsm1f  于 2021-09-08  发布在  Java
关注(0)|答案(5)|浏览(436)

我正在绘制Pandas图,需要比当前时间早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变量的情况下执行相同的操作?

cyvaqqii

cyvaqqii1#

它可以很简单: plotform = datetime.datetime.now() - datetime.timedelta(hours=-3)

x7rlezfr

x7rlezfr2#

from datetime import datetime, timedelta

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

plotfrom.strftime("%Y-%m-%d %H:%M:%S")
tyg4sfes

tyg4sfes3#

使用f字符串:

import datetime
todaydate = datetime.datetime.now()
>>> print(f"{(todaydate-datetime.timedelta(hours=3)).strftime('%Y-%m-%d %H:%M:%S')} is three hours earlier than {todaydate.strftime('%Y-%m-%d %H:%M:%S')}")
2021-07-09 08:16:23 is three hours earlier than 2021-07-09 11:16:23
5t7ly7z5

5t7ly7z54#

我喜欢这样的东西 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 .

zzlelutf

zzlelutf5#

你可以在线计算日期时间。

import datetime
now_minus_three_hours = (datetime.datetime.now() - datetime.timedelta(hours=3)).strftime("%Y-%m-%d %H:%M:%S")
print("Three hours ago from local time is:", now_minus_three_hours)

当地时间三小时前是:2021-07-09 07:18:16

相关问题