Skip to content
Advertisement

Split Time range into multiple time periods based on interval in Python

I have a time-range and an interval, I need to split the time range into multiple time periods based on interval value.

For example, time range is 9:30 to 11:30 and the interval is 30, the output time periods should be in a list as datetime objects

Output:

JavaScript

Advertisement

Answer

You can do arithmetic on datetime objects by adding timedelta objects.

You probably need to decide exactly what behaviour is required if the interval per period is not an exact divisor of the total, but this example would give a final short period in that case.

JavaScript

This gives (with newlines inserted for readability):

JavaScript

For the string output format that you want, you could do something like this:

JavaScript

to give:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement