0

I have a start date and an end date, how do I calculate the hours of each day between two dates?

start date 2020-01-01 10:00
end date 2020-01-04 15:00

Example of sum of hours period between start date and end date:

2020-01-01 14 hours
2020-01-02 24 hours
2020-01-03 24 hours
2020-01-04 15 hours
James
  • 32,991
  • 4
  • 47
  • 70
  • Welcome to Stack Overflow! Please add what you have tried so far, so we can see where you get stuck – Energya Mar 10 '20 at 12:28
  • 1
    Does this answer your question? [How do I find the time difference between two datetime objects in python?](https://stackoverflow.com/questions/1345827/how-do-i-find-the-time-difference-between-two-datetime-objects-in-python) – Energya Mar 10 '20 at 12:29

2 Answers2

1

First you need to convert the times from strings to timestamp objects using the datetime module. After that, you can step along each day and calculate the hours left in the day. Finally add a check if the date is the same as the end date, use the hours in the end date for the time difference.

Reading in the datetimes from a string requires using the date-formatting syntax. Basically, a percent sign followed by a letter is used to represent a standard portion of a datetime string. I.e. %H is the hours in 24-hour format, %Y is the year, %m is month, and %M is minutes. The dashes, spaces, slashes, colons and dots need to match what is in the string as well. For a complete list see this site: https://strftime.org/

import datetime as dt

start_date = '2020-01-01 10:00'
end_date = '2020-01-04 15:00'

start = dt.datetime.strptime(start_date, '%Y-%m-%d %H:%M')
end = dt.datetime.strptime(end_date, '%Y-%m-%d %H:%M')

def hours_left(ts):
    return 24-(ts.hour + ts.minute / 60)

hours = []
day = start
for i in range(d.days + bool(d.seconds)):
    if day.date() != end.date():
        h = hours_left(day)
    else:
        h = end.hour + end.minute / 60
    hours.append((day.date(), h))
    day = day + dt.timedelta(hours=h)

hours
# returns:
[(datetime.date(2020, 1, 1), 14.0),
 (datetime.date(2020, 1, 2), 24.0),
 (datetime.date(2020, 1, 3), 24.0),
 (datetime.date(2020, 1, 4), 15.0)]

Here hours is a list of tuples containing the date and the hours. If you want it as a list of strings you can pass it through a string formatter.

hours_str = [f'{d.strftime("%Y-%m-%d")}  {h:.0f} hours' for d, h in hours]
hours_str
# returns
['2020-01-01  14 hours',
 '2020-01-02  24 hours',
 '2020-01-03  24 hours',
 '2020-01-04  15 hours']
James
  • 32,991
  • 4
  • 47
  • 70
  • I think this is missing a special case for when `start` and `end` are on the same day, but otherwise fine. – tobias_k Mar 10 '20 at 12:43
0

You probably want to use the datetime module: define your start and end date using datetime objects and simply substract one to the other.

You will end up with a timedelta object from which you can extract the number of seconds (tip: there is 86400 seconds per day).

StinGer
  • 76
  • 1
  • 5