在给定范围内生成随机时间戳? [英] Generate Random Timestamp in a given range?
本文介绍了在给定范围内生成随机时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试执行以下操作:
start=input("选择开始日期,格式示例:Jan 01 00:00:00")end=input("选择结束日期")如果开始>结束:开始,结束=结束,开始打印(随机时间(开始,结束))
输出:
<预><代码>>>>8 月 5 日 13:15:59我曾尝试使用 random.randint,但如果我选择一个范围,例如:00:00:00 &&01:00:00,唯一随机的部分是小时、分钟和秒将被忽略(因为我在做 random.randint(0,0)).
我该如何正确地做到这一点?
提前致谢!
解决方案
您可以使用以下内容:
from random import randrange导入时间start_timestamp = time.mktime(time.strptime('Jun 1 2010 01:33:00', '%b %d %Y %I:%M:%S'))end_timestamp = time.mktime(time.strptime('Jun 1 2017 12:33:00', '%b %d %Y %I:%M:%S'))def randomize_time(start_timestamp,end_timestamp):return time.strftime('%b %d %Y %I:%M:%S', time.localtime(randrange(start_timestamp,end_timestamp)))
I'm trying to do something like:
start=input("select starting date, format example : Jan 01 00:00:00")
end=input("select ending date")
if start>end:
start,end=end,start
print(randomize_time(start,end))
Output:
>>> Aug 05 13:15:59
I have tried using random.randint, but if I select a range like: 00:00:00 && 01:00:00, the only part that is randomized is the hour, minutes and seconds will be ignored (since I'm doing random.randint(0,0)).
How would I do that properly?
Thanks in advance SO!
解决方案
You can use something as below:
from random import randrange
import time
start_timestamp = time.mktime(time.strptime('Jun 1 2010 01:33:00', '%b %d %Y %I:%M:%S'))
end_timestamp = time.mktime(time.strptime('Jun 1 2017 12:33:00', '%b %d %Y %I:%M:%S'))
def randomize_time(start_timestamp,end_timestamp):
return time.strftime('%b %d %Y %I:%M:%S', time.localtime(randrange(start_timestamp,end_timestamp)))
这篇关于在给定范围内生成随机时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文