Home > Net >  Dividing the data timeline into subset of date ranges of dictioanries in a list in python
Dividing the data timeline into subset of date ranges of dictioanries in a list in python

Time:11-29

I am converting date timeline into smaller date time segments based on the frequency in minutes from start time to end time. Input:

start_time = '2022-11-20-09:48:00'
last_time = '2022-11-20-08:48:00'
frequency = 300 # seconds so it is 5 minutes

what I tried so far

from datetime import datetime

def time_divider(s_time, e_time, frequency):
    st_obj = datetime.strptime(s_time, '%Y-%m-%d-%H:%M:%S')
    start_range = st_obj.timestamp()
    end_range = datetime.strptime(e_time, '%Y-%m-%d-%H:%M:%S').timestamp()
    date_segments = []
    a = int(start_range)
    b = int(end_range 1)
    for i in range(a, b 1):
        date_segments.append({datetime.fromtimestamp(i):  datetime.fromtimestamp(i   frequency)})
        i = i   frequency
    return date_segments

date_s = time_divider(start_time, last_time, 300)
print(date_s)

current output:

[]

expected output and the output should come in this sequence

{datetime.datetime(2022, 11, 20, 9, 48): datetime.datetime(2022, 11, 20, 9, 52),datetime.datetime(2022, 11, 20, 9, 53): datetime.datetime(2022, 11, 20, 9, 57), datetime.datetime(2022, 11, 20, 9, 57): datetime.datetime(2022, 11, 20, 10, 02 ), ...}

CodePudding user response:

start_time should be less than end_time

like:

start_time = '2022-11-20-08:48:00'

last_time = '2022-11-20-09:48:00'

and if we hadd 5 minutes in 48 it would become 53 not 52 as you have mentioned in expected output.

Here is the solution which might solve the problem.

from datetime import datetime, timedelta


start_time = '2022-11-20-08:48:00'
last_time = '2022-11-20-09:48:00'
frequency = 300  # seconds so it is 5 minutes


def time_divider(s_time, e_time, frequency):
    st_obj = datetime.strptime(s_time, '%Y-%m-%d-%H:%M:%S')
    end_range = datetime.strptime(e_time, '%Y-%m-%d-%H:%M:%S')
    date_segments = []
    while st_obj <= end_range:
        old_st_obj = st_obj
        st_obj = st_obj   timedelta(seconds=frequency)
        date_segments.append({old_st_obj: st_obj})
    return date_segments


date_s = time_divider(start_time, last_time, 300)
print(date_s)
  • Related