扫码关注官方订阅号
实现效果如下:如规定时间10:00:00~18:00:00 我想随机取里面的时间里面
认证0级讲师
提供个思路,不写代码了。你把这个时间段转换成总共的秒数。定一个用秒数表示的start_time和end_time;random(start_time,end_time);然后转换成时间呗。
import datetime import random def random_datetime(start_datetime, end_datetime): delta = end_datetime - start_datetime inc = random.randrange(delta.total_seconds()) return start_datetime + datetime.timedelta(seconds=inc) if __name__=='__main__': start_datetime = datetime.datetime(2016, 8, 17, 10, 0, 0) end_datetime = datetime.datetime(2016, 8, 17, 18, 0, 0) dt = random_datetime(start_datetime, end_datetime) print(dt)
結果:
2016-08-17 11:59:04
我回答過的問題: Python-QA
楼上的是一种好思路,我再提供一个low一点的写法
from random import randint h, m, s = randint(10, 18), 0, 0 if h != 18: m = randint(0, 59) s = randint(0, 59) print '%d:%02d:%02d' % (h, m, s)
from random import randint "{}:{}:{}".format(randint(10,17),randint(0,59),randint(0,59))
写了一个生成上班签到记录的。
#python生成随机时间段 #2016年12月6日18:34:26 codegay #参考资料 http://www.runoob.com/python/python-date-time.html #Python 取一个时间段里面的时间 https://segmentfault.com/q/1010000006617581 import time import random st = "2016-12-6 18:40:36" et = "2016-12-16 18:40:44" tf = "%Y-%m-%d %H:%M:%S" name = """11 22 33 44 狗三 猫4 猪八""" namelist = name.splitlines() count = len(namelist) print(namelist) def random_time(st,et,count=1): start = int(time.mktime(time.strptime(st,tf))) end = int(time.mktime(time.strptime(et,tf))) mktime = random.sample(range(start,end),count) strtime = [time.strftime(tf,time.localtime(r)) for r in sorted(mktime)] return strtime result = random_time(st,et,count) random.shuffle(namelist)#打乱名单的顺序 for t in zip(result,namelist): print(*t) """ 输出: ['11', '22', '33', '44', '狗三', '猫4', '猪八'] 2016-12-08 04:00:26 33 2016-12-09 11:16:06 猪八 2016-12-12 08:13:51 狗三 2016-12-12 11:57:52 猫4 2016-12-12 12:56:37 11 2016-12-12 22:20:52 44 2016-12-16 02:47:04 22 """
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
提供个思路,不写代码了。你把这个时间段转换成总共的秒数。
定一个用秒数表示的start_time和end_time;
random(start_time,end_time);
然后转换成时间呗。
結果:
我回答過的問題: Python-QA
楼上的是一种好思路,我再提供一个low一点的写法
写了一个生成上班签到记录的。