Search code examples
pythonpython-datetime

Python - Count number of date/time iterations between 2 dates using freq


I am trying to figure out how to calculate number of iterations of datetimes between 2 dates using a specific frequency (1D 3D 3H 15T)

for example:

freq = '3H'
start = datetime.datetime(2018, 8, 14, 9, 0, 0)
end= datetime.datetime(2018, 8, 15)
total = func(start, end, freq)

if freq = '3H' total would be 5.

if freq = '30T' total would be 30

what would func look like?

EDIT I'm leaving my original question up there, and adding details I failed to add originally in order to keep things as simple as possible.

In the code I am working on, I have a Pandas DataFrame with a DateTimeIndex. I needed to calculate the number of rows since a specific time(above). I thought about creating a DataFrame starting from that time and filling in the gaps, and counting rows like that, but that seems silly now.

the function I ended up using (with the parsing) is this:

def periods(row, time_frame):
    start = datetime.datetime(2018, 8, 14, 9, 0, 0)
    end = row.name
    t = time_frame[-1:]
    n = int(re.findall('\d+',time_frame)[0])
    if t is 'H':
        freq = datetime.timedelta(hours=n)
    elif t is 'T':
        freq = datetime.timedelta(minutes=n)
    else:
        freq = datetime.timedelta(days=n)
    count = 0
    while start < end:
        start += freq
        count += 1
    return count

and I call it from my dataframe(candlesticks) like this:

candlesticks['n'] = candlesticks.apply(lambda x: periods(x, candlesticks.index.freqstr), axis=1)

Solution

  • Use the timedelta module in the datetime library, and from there it's the same as comparing numbers essentially.

    from datetime import timedelta
    
    freq = timedelta(hours=3)
    
    def periods(frequency, start, end):
        count = 0
        while start < end:
            start += frequency
            count += 1
        return count
    
    p = periods(freq, start, end)
    
    print(p)
    >> 5