Stefano Lazzaro
Stefano Lazzaro

Reputation: 487

Python get datetime intervals of x minutes between two datetime objects

How can I get the list of intervals (as 2-tuples) of x minutes between to datetimes? It should be easy but even pandas.date_range() returns exacts intervals, dropping end time. For example:

In:

from = '2023-01-05 16:01:58'
to   = '2023-01-05 17:30:15'
x    = 30

Expected:

[
    ('2023-01-05 16:01:58', '2023-01-05 16:30:00'), 
    ('2023-01-05 16:30:00', '2023-01-05 17:00:00'), 
    ('2023-01-05 17:00:00', '2023-01-05 17:30:00'), 
    ('2023-01-05 17:30:00', '2023-01-05 17:30:15')
]

Upvotes: 1

Views: 76

Answers (1)

Laurent
Laurent

Reputation: 13478

Here is one way to do it with Pandas to_datetime, DateOffset and dt.ceil:

import pandas as pd
from pandas.tseries.offsets import DateOffset


from_date = pd.to_datetime("2023-01-05 16:01:58")
to_date = pd.to_datetime("2023-01-05 17:30:15")
freq = "30min"

intervals = []
start = pd.Series(from_date)
while True:
    end = (start + DateOffset(minutes=1)).dt.ceil(freq)
    if end[0] >= to_date:
        intervals.append((str(start[0]), str(pd.to_datetime(to_date))))
        break
    intervals.append((str(start[0]), str(end[0])))
    start = end

Then:

print(intervals)
# Output
[
    ("2023-01-05 16:01:58", "2023-01-05 16:30:00"),
    ("2023-01-05 16:30:00", "2023-01-05 17:00:00"),
    ("2023-01-05 17:00:00", "2023-01-05 17:30:00"),
    ("2023-01-05 17:30:00", "2023-01-05 17:30:15"),
]

Upvotes: 1

Related Questions