python获取指定时间段内的随机时间-random

场景:取N个07:30:00-09:30:33之间的随机时间

import random
st = "07:30:00"
et = "09:30:33"

def time2seconds(t):
    h,m,s = t.strip().split(":")
    return int(h) * 3600 + int(m) * 60 + int(s)

def seconds2time(sec):
    m,s = pmod(sec,60)
    h,m = pmod(m,60)
    return "%02d:%02d:%02d" % (h,m,s)

sts = time2seconds(st) #sts==27000
ets = time2seconds(et) #ets==34233

rt = random.sample(range(sts,ets),10)
#rt == [28931, 29977, 33207, 33082, 31174, 30200, 27458, 27434, 33367, 30450]
 
rt.sort() #对时间从小到大排序
  
for r in rt:
    print(seconds2time(r))

"""
输出:
07:43:12
07:54:31
08:08:33
08:27:46
08:46:53
08:48:17
08:55:20
08:59:16
09:10:23
09:15:58
"""

从代码中可以发现思路是把时间转成秒数后,那么就可以用range生07:30-09:30之间的时间秒数,再用random.sample从中取出个N个秒数,最后再把秒数转成所需要的时间格式。

链接:https://www.php.cn/python-tutorials-357630.html

为美好的生活奋斗!
原文地址:https://www.cnblogs.com/ethtool/p/14367745.html