Search code examples
pythonpython-3.xpython-datetime

Change, reset and increment time in python


I need to increment time in python and if the value of the range in loop increments, I need to set time to the original value.

example

start_time = '0230'
start_time = datetime.strptime(start_time, '%H%M')

difference_time = '0030'
difference_time = datetime.strptime(differece_time, '%H%M')

differnce_delta = timedelta(
    hours=difference.hour, minutes=difference.minute)

listvar = [5, 3, 4]

for i in range(3):
    x = listvar[i]
    for loop in range(x)
        print(f'{start_time.hour}:{start_time.minute}')
        start_time += difference_delta

Now if the the value of i becomes 2, I want start_time to get back to original value i.e 0230.


Solution

  • You can use another variable as a place holder for the original value.

        start_time = '0230'
        start_time_holder = '0230'
        start_time = datetime.strptime(start_time, '%H%M')
    
        difference_time = '0030'
        difference_time = datetime.strptime(differece_time, '%H%M')
    
        differnce_delta = timedelta(
            hours=difference.hour, minutes=difference.minute)
    
        listvar = [5, 3, 4]
    
        for i in range(5):
            start_time = start_time_holder
            x = listvar[i]
            for loop in range(x):
                print(f'{start_time.hour}:{start_time.minute}')
                start_time += difference_delta
    

    FYI: you would get a index out of range error at x = listvar[i] because the range is 5 but the list length is only 3