时分时间划分到不同时间区间段,Python

x33g5p2x  于2022-07-22 转载在 Python  
字(0.7k)|赞(0)|评价(0)|浏览(374)

用Python实现一个功能,把一个时间划入到不同的时间范围内,比如23:05,把这个时间划入到(23,24)区间内。又比如0:56,划入(0,1)范围内。

import datetime
import random

# 生成随机测试时间数量
TIME_COUNT = 20

def my_time():
    time_x = []
    for i in range(24):
        time_x.append((i, i + 1))

    times = []
    while True:
        h = random.randint(0, 23)
        m = random.randint(0, 59)
        t = datetime.time(hour=h, minute=m)
        for tx in time_x:
            if tx[0] <= t.hour < tx[1]:
                times.append((tx, t))
                break

        if len(times) > TIME_COUNT:
            break

    for t in times:
        print(f'{t[1].strftime("%H:%M")} @ {t[0]}')

if __name__ == '__main__':
    my_time()

输出:

08:00 @ (8, 9)
01:37 @ (1, 2)
15:03 @ (15, 16)
06:19 @ (6, 7)
18:11 @ (18, 19)
10:49 @ (10, 11)
10:10 @ (10, 11)
05:51 @ (5, 6)
11:22 @ (11, 12)
00:34 @ (0, 1)
02:30 @ (2, 3)
18:57 @ (18, 19)
21:37 @ (21, 22)
09:44 @ (9, 10)
07:38 @ (7, 8)
04:21 @ (4, 5)
07:07 @ (7, 8)
10:47 @ (10, 11)
20:12 @ (20, 21)
08:40 @ (8, 9)
03:46 @ (3, 4)

相关文章