Add 15 minutes to current timestamp using timedelta

philiporlando picture philiporlando · Apr 3, 2017 · Viewed 14.5k times · Source

The title says it all. I am writing a script to make scheduled GET requests to an API. I want to print when the next API call will be made, which would be 15 minutes from the previous call.

I'm very close, but have been running into the following error: TypeError: a float is required

Here's my code:

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   

I can get things to work (sort of) when changing the following line:

print "Next request @ " + str(nextTime)

However, this prints a timestamp with six decimal places for milliseconds. I want to keep things in the %Y-%m-%d %H:%M:%S format.

Answer

Derlin picture Derlin · Apr 3, 2017

You don't need to use datetime.fromtimestamp since nextTime is already a datetime object (and not a float). So, simply use:

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