場景:取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