昊天SEO

python随机生成时间

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())

 

2020-1
第二种方法:
# 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')

 

 

 

网站的维护离不开大家的支持鼓励,捐赠让我更有动力走的更远&& 也可以关注我的微信公众号,发布更多的干货
本文网址:https://www.168seo.cn/python/2077.html

评论 1

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #1

    专业贴,厉害!

    烟台阿里巴巴12个月前 (08-04)回复