How would I generate a random date that has to be between two other given dates?
The function"s signature should be something like this:
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
and would return a date such as:
2/4/2008 7:20 PM
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 example (output is almost in the format you specified, other than
0 padding - blame the American time format conventions):
import random import time def str_time_prop(start, end, time_format, prop): """Get a time at a proportion of a range of two formatted times. start and end should be strings specifying times formatted 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, time_format)) etime = time.mktime(time.strptime(end, time_format)) ptime = stime + prop * (etime - stime) return time.strftime(time_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()))
Python Workout isn’t designed to teach you Python, although I hope and expect that you’ll learn quite a bit along the way. It is meant to help you improve your understand- ing of Python and how to...
Data scientist has been called “the sexiest job of the 21st century,” presumably by someone who has never visited a fire station. Nonetheless, 23/09/2020
The genesis of this book began in 2012. Hadoop was being explored in mainstream organizations, and we believed that information architecture was about to be transformed. For many years, business intel...
Roger Jennings is an author and consultant specializing in Microsoft .NET n-tier database applications and data-intensive Windows Communication Foundation (WCF) Web services with SQL Server. He’s be...