tolmun
tolmun

Reputation: 11

python - timedelta and two time ranges

I would like to find how many hours from timedelta are inside Day and Night range.

Time-Start:

>>> dt_start = datetime.datetime(2012, 8, 19, 16, 0)

Time-Stop:

>>> dt_stop = datetime.datetime(2012, 8, 20, 3, 0)

Timedelta:

>>> dtd = dt_stop - dt_start
>>> print(dtd.seconds//3600)
>>> 11

Time ranges:

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

Answers (1)

Martijn Pieters
Martijn Pieters

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

Related Questions