This article introduces the implementation code of python to obtain random non-repeating time points within a specified time period
The following is my code:
#2016-12-10 7:06:29 codegay 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 """
You can find from the code that the idea is to convert the time into seconds, then you can use range to generate the time between 07:30-09:30 Seconds of time, then use random.sample to extract N seconds from it, and finally convert the seconds into the required time format.
>>> "09:30:00" > "9:30:00" False >>> "09:30:00" == "9:30:00" False
Judgment based on string may appear like the above situation. I feel that after unified conversion into numbers The calculation is more reliable.
UNIX time, or POSIX time is UNIX or UNIX-like The time representation used by the system: the total number of seconds from 0:00:00 on January 1, 1970 UTC to the present.
The time converted into seconds within any 24 hours of the day is exactly equal to the timestamp of January 1, 1970 UTC. So if necessary, you can use the Programming languagebuilt-in timestampfunction for conversion.
The above is the detailed content of Python implementation code to obtain random non-repeating time points within a specified time period. For more information, please follow other related articles on the PHP Chinese website!