在其他两个日期之间生成一个随机日期

编程入门 行业动态 更新时间:2024-10-23 21:28:00
本文介绍了在其他两个日期之间生成一个随机日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何生成一个必须介于另外两个给定日期之间的随机日期?

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

并且会返回一个日期,例如:2/4/2008 7:20 PM

and would return a date such as: 2/4/2008 7:20 PM

推荐答案

将两个字符串都转换为时间戳(以您选择的分辨率,例如毫秒、秒、小时、天等),从较晚的时间减去较早的时间,乘以您的随机数数字(假设它分布在 range [0, 1] 中)具有该差异,并再次添加到较早的一个.将时间戳转换回日期字符串,并且您在该范围内有一个随机时间.

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 示例(输出几乎是您指定的格式,除了 0 填充 - 怪美国时间格式约定):

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

更多推荐

在其他两个日期之间生成一个随机日期

本文发布于:2023-10-23 22:43:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1522218.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!