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']