0

So I'm trying to print the total hours in intervals between a start date and an end date in python as follows:

@app.route('/test/')
def test():

date_format = "%Y-%m-%d %H:%M:%S"
start_date_time = datetime.strptime("2018-10-16 07:00:00", date_format)
end_date_time = datetime.strptime("2018-10-18 22:00:00", date_format)

def daterange(start_date_time, end_date_time):
    for n in range(int ((end_date_time - start_date_time).days)):
        yield start_date_time + timedelta(n)

for single_date in daterange(start_date_time, end_date_time):
    def get_delta(start_date_time, end_date_time):
        delta = end_date_time - start_date_time
        return delta

# Split time in hours
delta = get_delta(start_date_time,end_date_time)
for i in range(delta.days * 24 + 1): # THIS IS ONLY CALCULATING 24HRS FROM TIME GIVEN START TIME NOT TILL THE SELECTED END TIME SO I'M ONLY GETTING AN EXACT 24 HOUR RANGE
    currtime = start_date_time + timedelta(hours=i)

    print (currtime)
return ("done")

By This i'm only managing to get the first 24 Hours from the selected date, but I wish to keep on counting and get all hours till the selected end date.

1

1 Answer 1

2

You might be overthinking it.

from datetime import datetime, timedelta

date_format = "%Y-%m-%d %H:%M:%S"
start_date_time = datetime.strptime("2018-10-16 07:00:00", date_format)
end_date_time = datetime.strptime("2018-10-18 22:00:00", date_format)

def get_delta(l, r):
    return abs(int((l-r).total_seconds())) / 3600

for h in range(int(get_delta(start_date_time, end_date_time))):
    print((start_date_time + timedelta(0, h*3600)).strftime(date_format))
Sign up to request clarification or add additional context in comments.

4 Comments

But this just gives me the total amount of hours between both dates and won't print hour intervals... thanks for your help
Ahh. That's an odd thing to do, but OK. Edited.
ok this seems to work well, thanks for your answer. I will mark as correct, but I have one question if you can help, is it possible to loop within the dates after this and do a function for each day, ex: 16/10/2018 > do something ... continue... 17/10/2018 > do something .... continue ... 18/10/2018 > do something. Thanks again
Yes - you could use something like new_time = start_date_time + timedelta(0, h*3600) in the loop. Then if new_time.hour == 0: will run code every time there's a new day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.