如何生成必须在其他两个给定日期之间的随机日期?
该函数的签名应如下所示:
random_date("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34) ^ ^ ^ date generated has date generated has a random number to be after this to be before this
并返回一个日期,例如: 2/4/2008 7:20 PM
2/4/2008 7:20 PM
将两个字符串都转换为时间戳(以您选择的分辨率为单位,例如毫秒,秒,小时,天,等等),从后一个减去前一个,将随机数(假设分布在中range [0, 1])乘以该差,然后再次加较早的。将时间戳转换回日期字符串,并且您在该范围内有一个随机时间。
range [0, 1]
Python示例(输出几乎是您指定的格式,而不是0填充-归咎于美国时间格式约定):
0
import random import time def str_time_prop(start, end, format, prop): """Get a time at a proportion of a range of two formatted times. start and end should be strings specifying times formated in the given format (strftime-style), giving an interval [start, end]. prop specifies how a proportion of the interval to be taken after start. The returned time will be in the specified format. """ stime = time.mktime(time.strptime(start, format)) etime = time.mktime(time.strptime(end, format)) ptime = stime + prop * (etime - stime) return time.strftime(format, time.localtime(ptime)) def random_date(start, end, prop): return str_time_prop(start, end, '%m/%d/%Y %I:%M %p', prop) print(random_date("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", random.random()))