更新给定范围内的每第n个元素

1 投票
3 回答
78 浏览
提问于 2025-04-14 18:12

我有一个数字N=12,

我想在1到12之间,每3个元素更新一次。

举个例子:我正在计算当前的小时(比如说早上6点),然后加上4个小时,第一组3个元素就变成“6-10”,接着再对下一组3个元素加4个小时,依此类推……

所以我期望的输出是:

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

我有这样的东西:

#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

但是我得到的输出是所有12个元素都是6-10(时间都是一样的)。

3 个回答

0

我把我的代码拆分成了更小的部分,这样你就能更容易理解datetime模块的概念了。

#Apart from datetime, import timedelta which is meant for adding time
from datetime import datetime, timedelta

#Import module for timezone
import pytz

#Get your time zone(I guess you're from India)
tz_ch = pytz.timezone('Asia/Kolkata')

#Get current time of your time zone
tz_ch = datetime.now(tz_ch)

#iterate in the range of 12
for i in range(12):
    
    #if i is divided by 3 add 4 hrs to current_time(also i should not be 0)
    if i != 0 and i % 3 == 0: tz_ch = tz_ch + timedelta(hours=4)

    #Always add 4 hours to to_time
    to_time = tz_ch + timedelta(hours=4)

    #Get the time component inturn hour component of from time
    fr = tz_ch.time()
    fr = f'{fr:%H}'

    #Get the time component inturn hour component of to_time
    to = to_time.time()
    to = f'{to:%H}'
    
    #time range
    time_range = f'{fr} - {to}'
    print(i+1, time_range)

'''Output:
1 20 - 23
2 20 - 23
3 20 - 23
4 23 - 02
5 23 - 02
6 23 - 02
7 02 - 05
8 02 - 05
9 02 - 05
10 05 - 08
11 05 - 08
12 05 - 08
'''
0

你可以让 datetime 模块来帮你处理这个问题。你可以创建一个日期时间对象,然后加上一个 timedelta 对象:

from datetime import datetime, timedelta, timezone

n = 12
current_datetime = datetime.now(tz=timezone.utc)
for i in range(1, n + 1, 3):
    added_four = current_datetime + timedelta(hours=4)
    for j in range(3):
        print(f"{i+j} {current_datetime.hour}-{added_four.hour}")
    current_datetime += timedelta(hours=4)

输出(以UTC时间显示):

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-3
11 23-3
12 23-3
0

现在推荐获取当前小时的方法和你代码里的不一样。datetime.utcnow() 这个方法已经不再推荐使用了。

你可以试试这个:

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}")

输出结果:

 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

撰写回答