Search code examples
pythonarrayspython-3.xlistdynamic-programming

Update every nth element of given a range


I have N=12 and between 1 to 12 (in N) I want every 3 elements to be updated.

For example: I am calculating the current hour(say 6am) and add 4 hours to start with "6-10" for the 1st 3 rows and add 4hrs for the next 3 and so on...

So The expected output is :

1 6-10
2 6-10
3 6-10
4 10-14
5 10-14
6 10-14
7 14-18
8 14-18
9 14-18
10 18-22
11 18-22
12 18-22

I have somethinglike this:

#utc_hour is the current utc hour calculated
from datetime import datetime
utc_time = datetime.utcnow()
utc_year = utc_time.year
utc_month = utc_time.month
utc_day = utc_time.day
utc_hour = utc_time.hour
utc_minute = utc_time.minute
minute = []
hour =[]
day = []
month = []
week = []
_hour = utc_hour
count = 0
n= 3
jobs = 12
while count <= int(jobs):
    if layer == 'get' :  
        
        minute.append('0-59')
        incr_hour = _hour+4
        gen_hour = str(_hour)+'-'+str(incr_hour)   
        a = [hour.append(gen_hour)]
        print(count,x,n,hour)
    count+=1

and the output i get is all the 12 elements with 6-10 (the same hour)


Solution

  • The currently recommended way to get the current hour differs from what's in your code. datetime.utcnow() is deprecated.

    Try this:

    import datetime
    
    hour = datetime.datetime.now(datetime.UTC).hour
    
    N = 12
    
    for i in range(N):
        hh = (hour + 4 * (i//3)) % 24
        print(f"{i+1:>2} {hh:02d}-{(hh+4)%24:02d}")
    

    Output:

     1 11-15
     2 11-15
     3 11-15
     4 15-19
     5 15-19
     6 15-19
     7 19-23
     8 19-23
     9 19-23
    10 23-03
    11 23-03
    12 23-03