使用 timedelta 将 15 分钟添加到当前时间戳

phi*_*ndo 9 python datetime timestamp typeerror timedelta

标题说明了一切。我正在编写一个脚本来向 API 发出预定的 GET 请求。我想打印下一次 API 调用的时间,距上一次调用需要 15 分钟。

我非常接近,但一直遇到以下错误: TypeError: a float is required

这是我的代码:

import time, datetime
from datetime import datetime, timedelta

while True:
    ## create a timestamp for the present moment:
    currentTime = datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
    print "GET request @ " + str(currentTime)

    ## create a timestamp for 15 minutes into the future:
    nextTime = datetime.datetime.now() + datetime.timedelta(minutes = 15)
    print "Next request @ " + str(datetime.datetime.fromtimestamp(nextTime).strftime("%Y-%m-%d %H:%M:%S")
    print "############################ DONE #############################"
    time.sleep(900) ## call the api every 15 minutes   
Run Code Online (Sandbox Code Playgroud)

更改以下行时,我可以让事情(有点)工作:

print "Next request @ " + str(nextTime)
Run Code Online (Sandbox Code Playgroud)

但是,这会打印一个带有六个小数位的时间戳,表示毫秒。我想保持%Y-%m-%d %H:%M:%S格式。

Der*_*lin 6

您不需要使用,datetime.fromtimestamp因为nextTime它已经是一个日期时间对象(而不是一个浮点数)。因此,只需使用:

nextTime = datetime.datetime.now() + datetime.timedelta(minutes = 15)
print "Next request @ " + nextTime.strftime("%Y-%m-%d %H:%M:%S")
Run Code Online (Sandbox Code Playgroud)