生成两个其他日期之间的随机日期 [英] Generate a random date between two other dates
问题描述
如何生成必须在两个其他给定日期之间的随机日期?
函数签名应该是这样的 -
How would I generate a random date that has to be between two other given dates? The functions signature should something like this-
randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
,并返回一个日期,如$
2/4/2008 7:20 PM
and would return a date such as- "2/4/2008 7:20 PM"
推荐答案
将两个字符串转换为时间戳(在您选择的分辨率中,例如毫秒,秒,小时,天,无论如何)从较晚的时候,将你的随机数乘以(假设它在[0,1]范围内分布),然后再加上前一个值。将时间戳转换回到日期字符串,并且您在该范围内有随机时间。
Convert both strings to timestamps (in your chosen resolution, e.g. milliseconds, seconds, hours, days, whatever), subtract the earlier from the later, multiply your random number (assuming it is distributed in the range [0, 1]) with that difference, and add again to the earlier one. Convert the timestamp back to date string and you have a random time in that range.
Python示例(输出几乎是您指定的格式,而不是0 padding - blame美国时间格式约定):
Python example (output is almost in the format you specified, other than 0 padding - blame the American time format conventions):
import random
import time
def strTimeProp(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 randomDate(start, end, prop):
return strTimeProp(start, end, '%m/%d/%Y %I:%M %p', prop)
print randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", random.random())
这篇关于生成两个其他日期之间的随机日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!