Reputation: 11
I would like to find how many hours from timedelta are inside Day and Night range.
>>> dt_start = datetime.datetime(2012, 8, 19, 16, 0)
>>> dt_stop = datetime.datetime(2012, 8, 20, 3, 0)
>>> dtd = dt_stop - dt_start
>>> print(dtd.seconds//3600)
>>> 11
Day = 7am-22pm
Night = 22pm-7am
For this example the right output will be:
Day hours: 6:00
Night hours: 5:00
I will be grateful for any help.
Upvotes: 1
Views: 1024
Reputation: 1121406
You'd need to specify the transition point for day and night, and calculate the delta to that and then the delta to the end-point:
day_start = 7
night_start = 22
day_hours = 0
night_hours = 0
if dt_start.hour < night_start:
dt_night = dt_start.replace(hour=night_start)
day_hours = (dt_night - dt_start).seconds // 3600
night_hours = (dt_end - dt_night).seconds // 3600
This is a rather naive setup, as it won't support multiple-day spans and such. Consider it a starting point.
Upvotes: 1