1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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', prop) for i in range(10): print randomDate("1/1/2008", "1/1/2016", random.random()) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<img class="aligncenter size-full wp-image-2103" src="http://hangzhou01.oss-cn-hangzhou.aliyuncs.com/old/2ca4b0a5835d086de19d68ab3cfcda85.jpg" alt="2020-1" width="614" height="529" /> 第二种方法: # import modules import random import datetime # create function accepting a single parameter, the year as a four digit number def get_random_date(year): # try to get a date try: return datetime.datetime.strptime('{} {}'.format(random.randint(1, 366), year), '%j %Y') # if the value happens to be in the leap year range, try again except ValueError: get_random_date(year) for i in xrange(200): print get_random_date('2016') |

专业贴,厉害!