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

Add 15 minutes to current timestamp using 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   

我可以在更改以下行时让事情正常工作(某种程度上):

print "Next request @ " + str(nextTime)

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

关闭。这里不需要使用fromtimestamp。您可以将最后几行缩减为:

import datetime as dt

nextTime = dt.datetime.now() + dt.timedelta(minutes = 15)
print "Next request @ " + dt.datetime.strftime(nextTime, "%Y-%m-%d %H:%M:%S")

也就是说,将datetime对象nextTime作为第一个参数传递给strftime

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

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

我一问这个问题就发现自己哪里做错了...

对于那些好奇的人,这里是解决方案:

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(nextTime.strftime("%Y-%m-%d %H:%M:%S"))
    print "############################ DONE #############################"
    time.sleep(900) ## call the api every 15 minutes

您只需使用时间戳即可实现:

import time
from datetime import datetime

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

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

我得到的输出是:

GET request @ 2017-04-03 16:31:34
Next request @ 2017-04-03 16:46:34
############################ DONE #############################