How would I generate a random date that has to be between two other given dates? The functions signature should something like this-
我如何生成一个随机的日期,它必须在另外两个给定的日期之间?函数的签名应该是这样的。
randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
and would return a date such as- "2/4/2008 7:20 PM"
并将返回一个日期,例如:“2/4/2008 7:20 PM”
22 个解决方案
#1
91
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.
将两个字符串转换为时间戳(在您选择的分辨率中,例如:毫秒、秒、小时、天数等),然后从后面减去前面的内容,将随机数相乘(假设它分布在[0,1]的范围内),然后再添加到前面的那个。将时间戳转换回日期字符串,并且在该范围内有一个随机时间。
Python example (output is almost in the format you specified, other than 0 padding - blame the American time format conventions):
Python示例(输出几乎是您指定的格式,而非0填充——将其归咎于美国时间格式约定):
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 %I:%M %p', prop)
print randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", random.random())
#2
82
from random import randrange
from datetime import timedelta
def random_date(start, end):
"""
This function will return a random datetime between two datetime
objects.
"""
delta = end - start
int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
random_second = randrange(int_delta)
return start + timedelta(seconds=random_second)
The precision is seconds. You can increase precision up to microseconds, or decrease to, say, half-hours, if you want. For that just change the last lines calculation.
精度是秒。你可以将精度提高到微秒,或者减少到,比如说,半小时,如果你想的话。因为这只会改变最后一行的计算。
example run:
示例运行:
d1 = datetime.strptime('1/1/2008 1:30 PM', '%m/%d/%Y %I:%M %p')
d2 = datetime.strptime('1/1/2009 4:50 AM', '%m/%d/%Y %I:%M %p')
print random_date(d1, d2)
output:
输出:
2008-12-04 01:50:17
#3
62
A tiny version.
一个小版本。
import datetime
import random
def random_date(start, end):
"""Generate a random datetime between `start` and `end`"""
return start + datetime.timedelta(
# Get a random amount of seconds between `start` and `end`
seconds=random.randint(0, int((end - start).total_seconds())),
)
Note that both start
and end
arguments should be datetime
objects. If you've got strings instead, it's fairly easy to convert. The other answers point to some ways to do so.
注意,开始和结束参数都应该是datetime对象。如果你有字符串,它很容易转换。其他的答案指出了这样做的一些方法。
#4
16
Updated answer
It's even more simple using Faker.
使用Faker更简单。
Installation
pip install faker
Usage:
from faker import Faker
fake = Faker()
fake.date_between(start_date='today', end_date='+30y')
# datetime.date(2025, 3, 12)
fake.date_time_between(start_date='-30y', end_date='now')
# datetime.datetime(2007, 2, 28, 11, 28, 16)
Old answer
It's very simple using radar
使用雷达很简单。
Installation
pip install radar
Usage
import datetime
import radar
# Generate random datetime (parsing dates from str values)
radar.random_datetime(start='2000-05-24', stop='2013-05-24T23:59:59')
# Generate random datetime from datetime.datetime values
radar.random_datetime(
start = datetime.datetime(year=2000, month=5, day=24),
stop = datetime.datetime(year=2013, month=5, day=24)
)
# Just render some random datetime. If no range is given, start defaults to
# 1970-01-01 and stop defaults to datetime.datetime.now()
radar.random_datetime()
#5
11
This is a different approach - that sort of works..
这是一种不同的方法。
from random import randint
import datetime
date=datetime.date(randint(2005,2025), randint(1,12),randint(1,28))
WAIITT - BETTER APPROACH
WAIITT——更好的方法
startdate=datetime.date(YYYY,MM,DD)
date=startdate+datetime.timedelta(randint(1,365))
#6
5
To chip in a pandas-based solution I use:
我使用的是基于pandas的解决方案:
import pandas as pd
import numpy as np
def random_date(start, end, position=None):
start, end = pd.Timestamp(start), pd.Timestamp(end)
delta = (end - start).total_seconds()
if position is None:
offset = np.random.uniform(0., delta)
else:
offset = position * delta
offset = pd.offsets.Second(offset)
t = start + offset
return t
I like it, because of the nice pd.Timestamp
features that allow me to throw different stuff and formats at it. Consider the following few examples...
我喜欢它,因为它很好。时间戳功能允许我在它上面抛出不同的东西和格式。考虑以下几个例子……
Your signature.
你的签名。
>>> random_date(start="1/1/2008 1:30 PM", end="1/1/2009 4:50 AM", position=0.34)
Timestamp('2008-05-04 21:06:48', tz=None)
Random position.
随机的位置。
>>> random_date(start="1/1/2008 1:30 PM", end="1/1/2009 4:50 AM")
Timestamp('2008-10-21 05:30:10', tz=None)
Different format.
不同的格式。
>>> random_date('2008-01-01 13:30', '2009-01-01 4:50')
Timestamp('2008-11-18 17:20:19', tz=None)
Passing pandas/datetime objects directly.
直接通过熊猫/ datetime对象。
>>> random_date(pd.datetime.now(), pd.datetime.now() + pd.offsets.Hour(3))
Timestamp('2014-03-06 14:51:16.035965', tz=None)
#7
5
Since Python 3 timedelta
supports multiplication with floats, so now you can do:
由于Python 3 timedelta支持浮点数的乘法,所以现在您可以这样做:
import random
random_date = start + (end - start) * random.random()
given that start
and end
are of the type datetime.datetime
. For example, to generate a random datetime within the next day:
给定的开始和结束都是类型datetime.datetime。例如,在第二天生成一个随机的datetime:
import random
from datetime import datetime, timedelta
start = datetime.now()
end = start + timedelta(days=1)
random_date = start + (end - start) * random.random()
#8
3
The easiest way of doing this is to convert both numbers to timestamps, then set these as the minimum and maximum bounds on a random number generator.
最简单的方法是将两个数字转换为时间戳,然后将它们设置为随机数生成器的最小和最大边界。
A quick PHP example would be:
一个简单的PHP例子是:
// Find a randomDate between $start_date and $end_date
function randomDate($start_date, $end_date)
{
// Convert to timetamps
$min = strtotime($start_date);
$max = strtotime($end_date);
// Generate random number using above bounds
$val = rand($min, $max);
// Convert back to desired date format
return date('Y-m-d H:i:s', $val);
}
This function makes use of strtotime()
to convert a datetime description into a Unix timestamp, and date()
to make a valid date out of the random timestamp which has been generated.
这个函数利用strtotime()将一个datetime描述转换为一个Unix时间戳,以及date(),以便从生成的随机时间戳中生成一个有效日期。
#9
3
You can Use Mixer
,
您可以使用搅拌机,
pip install mixer
and,
而且,
from mixer import generators as gen
print gen.get_datetime(min_datetime=(1900, 1, 1, 0, 0, 0), max_datetime=(2020, 12, 31, 23, 59, 59))
#10
2
Here is an answer to the literal meaning of the title rather than the body of this question:
这里是对标题的字面意思的回答,而不是这个问题的主体:
import time
import datetime
import random
def date_to_timestamp(d) :
return int(time.mktime(d.timetuple()))
def randomDate(start, end):
"""Get a random date between two dates"""
stime = date_to_timestamp(start)
etime = date_to_timestamp(end)
ptime = stime + random.random() * (etime - stime)
return datetime.date.fromtimestamp(ptime)
This code is based loosely on the accepted answer.
此代码松散地基于已接受的答案。
#11
2
Just to add another one:
再加一个:
datestring = datetime.datetime.strftime(datetime.datetime( \
random.randint(2000, 2015), \
random.randint(1, 12), \
random.randint(1, 28), \
random.randrange(23), \
random.randrange(59), \
random.randrange(59), \
random.randrange(1000000)), '%Y-%m-%d %H:%M:%S')
The day handling needs some considerations. With 28 you are on the secure site.
处理日常事务需要一些考虑。有28个你在安全的地方。
#12
1
- Convert your input dates to numbers (int, float, whatever is best for your usage)
- 将输入日期转换为数字(整数、浮点数、任何最适合您使用的)
- Choose a number between your two date numbers.
- 在两个日期之间选择一个数字。
- Convert this number back to a date.
- 将这个数字转换为日期。
Many algorithms for converting date to and from numbers are already available in many operating systems.
许多操作系统中已经有许多用于转换日期和数字的算法。
#13
1
What do you need the random number for? Usually (depending on the language) you can get the number of seconds/milliseconds from the Epoch from a date. So for a randomd date between startDate and endDate you could do:
你需要随机数来做什么?通常(取决于语言)您可以获得从一个日期开始的秒数/毫秒数。所以在startDate和endDate之间的随机日期可以做:
- compute the time in ms between startDate and endDate (endDate.toMilliseconds() - startDate.toMilliseconds())
- 计算startDate和endDate之间的时间(endDate.toMilliseconds() - startDate.toMilliseconds())
- generate a number between 0 and the number you obtained in 1
- 在0和你在1中得到的数字之间生成一个数字。
- generate a new Date with time offset = startDate.toMilliseconds() + number obtained in 2
- 生成一个新的日期,时间偏移= startDate.toMilliseconds() + 2中获得的数字。
#14
1
Here's a solution modified from emyller's approach which returns an array of random dates at any resolution
这是一个从emyller的方法修改的解决方案,它返回任意分辨率的随机日期数组。
import numpy as np
def random_dates(start, end, size=1, resolution='s'):
"""
Returns an array of random dates in the interval [start, end]. Valid
resolution arguments are numpy date/time units, as documented at:
https://docs.scipy.org/doc/numpy-dev/reference/arrays.datetime.html
"""
start, end = np.datetime64(start), np.datetime64(end)
delta = (end-start).astype('timedelta64[{}]'.format(resolution))
delta_mat = np.random.randint(0, delta.astype('int'), size)
return start + delta_mat.astype('timedelta64[{}]'.format(resolution))
Part of what's nice about this approach is that np.datetime64
is really good at coercing things to dates, so you can specify your start/end dates as strings, datetimes, pandas timestamps... pretty much anything will work.
这种方法的好处之一就是np。datetime64非常擅长于强制执行日期,所以您可以将开始/结束日期指定为字符串、datetimes、熊猫时间戳……几乎任何事情都可以。
#15
0
Conceptually it's quite simple. Depending on which language you're using you will be able to convert those dates into some reference 32 or 64 bit integer, typically representing seconds since epoch (1 January 1970) otherwise known as "Unix time" or milliseconds since some other arbitrary date. Simply generate a random 32 or 64 bit integer between those two values. This should be a one liner in any language.
在概念上很简单。根据您使用的语言,您将能够将这些日期转换为一些引用32或64位整数,通常表示自纪元(1970年1月1日)以来的秒数(1970年1月1日),也称为“Unix时间”,或自其他任意日期之后的毫秒数。在这两个值之间简单地生成一个32或64位整数。这应该是任何语言中的一行。
On some platforms you can generate a time as a double (date is the integer part, time is the fractional part is one implementation). The same principle applies except you're dealing with single or double precision floating point numbers ("floats" or "doubles" in C, Java and other languages). Subtract the difference, multiply by random number (0 <= r <= 1), add to start time and done.
在某些平台上,您可以生成一个时间为double(日期是整数部分,时间是小数部分是一个实现)。同样的原则适用于单或双精度浮点数(C、Java和其他语言中的“float”或“double”)。减去差异,乘以随机数(0 <= r <= 1),添加开始时间和完成。
#16
0
In python:
在python中:
>>> from dateutil.rrule import rrule, DAILY
>>> import datetime, random
>>> random.choice(
list(
rrule(DAILY,
dtstart=datetime.date(2009,8,21),
until=datetime.date(2010,10,12))
)
)
datetime.datetime(2010, 2, 1, 0, 0)
(need python dateutil
library – pip install python-dateutil
)
(需要python dateutil库- pip安装python-dateutil)
#17
0
Use ApacheCommonUtils to generate a random long within a given range, and then create Date out of that long.
使用ApacheCommonUtils在给定的范围内生成一个随机的长时间,然后创建日期。
Example:
例子:
import org.apache.commons.math.random.RandomData;
进口org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;
进口org.apache.commons.math.random.RandomDataImpl;
public Date nextDate(Date min, Date max) {
公开日期(日期、日期、日期、日期)
RandomData randomData = new RandomDataImpl();
return new Date(randomData.nextLong(min.getTime(), max.getTime()));
}
}
#18
0
I made this for another project using random and time. I used a general format from time you can view the documentation here for the first argument in strftime(). The second part is a random.randrange function. It returns an integer between the arguments. Change it to the ranges that match the strings you would like. You must have nice arguments in the tuple of the second arugment.
我用随机和时间做了另一个项目。我使用了一种通用格式,您可以在这里查看strftime()中的第一个参数的文档。第二部分是随机的。randrange函数。它在参数之间返回一个整数。将其更改为与您希望的字符串相匹配的范围。你必须在第二节课上有很好的论点。
import time
import random
def get_random_date():
return strftime("%Y-%m-%d %H:%M:%S",(random.randrange(2000,2016),random.randrange(1,12),
random.randrange(1,28),random.randrange(1,24),random.randrange(1,60),random.randrange(1,60),random.randrange(1,7),random.randrange(0,366),1))
#19
0
Pandas + numpy solution
熊猫+ numpy解决方案
import pandas as pd
import numpy as np
def RandomTimestamp(start, end):
dts = (end - start).total_seconds()
return start + pd.Timedelta(np.random.uniform(0, dts), 's')
dts is the difference between timestamps in seconds (float). It is then used to create a pandas timedelta between 0 and dts, that is added to the start timestamp.
dts是时间戳与秒之间的区别(float)。然后,它被用来在0到dts之间创建一个熊猫timedelta,它被添加到开始时间戳中。
#20
0
Based on the answer by mouviciel, here is a vectorized solution using numpy. Convert the start and end dates to ints, generate an array of random numbers between them, and convert the whole array back to dates.
基于mouviciel的答案,这里是一个使用numpy的矢量化解决方案。将开始和结束日期转换为ints,在它们之间生成一个随机数数组,并将整个数组转换为日期。
import time
import datetime
import numpy as np
n_rows = 10
start_time = "01/12/2011"
end_time = "05/08/2017"
date2int = lambda s: time.mktime(datetime.datetime.strptime(s,"%d/%m/%Y").timetuple())
int2date = lambda s: datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S')
start_time = date2int(start_time)
end_time = date2int(end_time)
random_ints = np.random.randint(low=start_time, high=end_time, size=(n_rows,1))
random_dates = np.apply_along_axis(int2date, 1, random_ints).reshape(n_rows,1)
print random_dates
#21
0
It's modified method of @(Tom Alsberg). I modified it to get date with milliseconds.
它修改了@(Tom Alsberg)的方法。我修改它以得到毫秒。
import random
import time
import datetime
def random_date(start_time_string, end_time_string, format_string, random_number):
"""
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.
"""
dt_start = datetime.datetime.strptime(start_time_string, format_string)
dt_end = datetime.datetime.strptime(end_time_string, format_string)
start_time = time.mktime(dt_start.timetuple()) + dt_start.microsecond / 1000000.0
end_time = time.mktime(dt_end.timetuple()) + dt_end.microsecond / 1000000.0
random_time = start_time + random_number * (end_time - start_time)
return datetime.datetime.fromtimestamp(random_time).strftime(format_string)
Example:
例子:
print TestData.TestData.random_date("2000/01/01 00:00:00.000000", "2049/12/31 23:59:59.999999", '%Y/%m/%d %H:%M:%S.%f', random.random())
Output: 2028/07/08 12:34:49.977963
输出:2028/07/08 12:34:49.977963
#22
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Create random datetime object."""
from datetime import datetime
import random
def create_random_datetime(from_date, to_date, rand_type='uniform'):
"""
Create random date within timeframe.
Parameters
----------
from_date : datetime object
to_date : datetime object
rand_type : {'uniform'}
Examples
--------
>>> random.seed(28041990)
>>> create_random_datetime(datetime(1990, 4, 28), datetime(2000, 12, 31))
datetime.datetime(1998, 12, 13, 23, 38, 0, 121628)
>>> create_random_datetime(datetime(1990, 4, 28), datetime(2000, 12, 31))
datetime.datetime(2000, 3, 19, 19, 24, 31, 193940)
"""
delta = to_date - from_date
if rand_type == 'uniform':
rand = random.random()
else:
raise NotImplementedError('Unknown random mode \'{}\''
.format(rand_type))
return from_date + rand * delta
if __name__ == '__main__':
import doctest
doctest.testmod()
#1
91
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.
将两个字符串转换为时间戳(在您选择的分辨率中,例如:毫秒、秒、小时、天数等),然后从后面减去前面的内容,将随机数相乘(假设它分布在[0,1]的范围内),然后再添加到前面的那个。将时间戳转换回日期字符串,并且在该范围内有一个随机时间。
Python example (output is almost in the format you specified, other than 0 padding - blame the American time format conventions):
Python示例(输出几乎是您指定的格式,而非0填充——将其归咎于美国时间格式约定):
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 %I:%M %p', prop)
print randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", random.random())
#2
82
from random import randrange
from datetime import timedelta
def random_date(start, end):
"""
This function will return a random datetime between two datetime
objects.
"""
delta = end - start
int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
random_second = randrange(int_delta)
return start + timedelta(seconds=random_second)
The precision is seconds. You can increase precision up to microseconds, or decrease to, say, half-hours, if you want. For that just change the last lines calculation.
精度是秒。你可以将精度提高到微秒,或者减少到,比如说,半小时,如果你想的话。因为这只会改变最后一行的计算。
example run:
示例运行:
d1 = datetime.strptime('1/1/2008 1:30 PM', '%m/%d/%Y %I:%M %p')
d2 = datetime.strptime('1/1/2009 4:50 AM', '%m/%d/%Y %I:%M %p')
print random_date(d1, d2)
output:
输出:
2008-12-04 01:50:17
#3
62
A tiny version.
一个小版本。
import datetime
import random
def random_date(start, end):
"""Generate a random datetime between `start` and `end`"""
return start + datetime.timedelta(
# Get a random amount of seconds between `start` and `end`
seconds=random.randint(0, int((end - start).total_seconds())),
)
Note that both start
and end
arguments should be datetime
objects. If you've got strings instead, it's fairly easy to convert. The other answers point to some ways to do so.
注意,开始和结束参数都应该是datetime对象。如果你有字符串,它很容易转换。其他的答案指出了这样做的一些方法。
#4
16
Updated answer
It's even more simple using Faker.
使用Faker更简单。
Installation
pip install faker
Usage:
from faker import Faker
fake = Faker()
fake.date_between(start_date='today', end_date='+30y')
# datetime.date(2025, 3, 12)
fake.date_time_between(start_date='-30y', end_date='now')
# datetime.datetime(2007, 2, 28, 11, 28, 16)
Old answer
It's very simple using radar
使用雷达很简单。
Installation
pip install radar
Usage
import datetime
import radar
# Generate random datetime (parsing dates from str values)
radar.random_datetime(start='2000-05-24', stop='2013-05-24T23:59:59')
# Generate random datetime from datetime.datetime values
radar.random_datetime(
start = datetime.datetime(year=2000, month=5, day=24),
stop = datetime.datetime(year=2013, month=5, day=24)
)
# Just render some random datetime. If no range is given, start defaults to
# 1970-01-01 and stop defaults to datetime.datetime.now()
radar.random_datetime()
#5
11
This is a different approach - that sort of works..
这是一种不同的方法。
from random import randint
import datetime
date=datetime.date(randint(2005,2025), randint(1,12),randint(1,28))
WAIITT - BETTER APPROACH
WAIITT——更好的方法
startdate=datetime.date(YYYY,MM,DD)
date=startdate+datetime.timedelta(randint(1,365))
#6
5
To chip in a pandas-based solution I use:
我使用的是基于pandas的解决方案:
import pandas as pd
import numpy as np
def random_date(start, end, position=None):
start, end = pd.Timestamp(start), pd.Timestamp(end)
delta = (end - start).total_seconds()
if position is None:
offset = np.random.uniform(0., delta)
else:
offset = position * delta
offset = pd.offsets.Second(offset)
t = start + offset
return t
I like it, because of the nice pd.Timestamp
features that allow me to throw different stuff and formats at it. Consider the following few examples...
我喜欢它,因为它很好。时间戳功能允许我在它上面抛出不同的东西和格式。考虑以下几个例子……
Your signature.
你的签名。
>>> random_date(start="1/1/2008 1:30 PM", end="1/1/2009 4:50 AM", position=0.34)
Timestamp('2008-05-04 21:06:48', tz=None)
Random position.
随机的位置。
>>> random_date(start="1/1/2008 1:30 PM", end="1/1/2009 4:50 AM")
Timestamp('2008-10-21 05:30:10', tz=None)
Different format.
不同的格式。
>>> random_date('2008-01-01 13:30', '2009-01-01 4:50')
Timestamp('2008-11-18 17:20:19', tz=None)
Passing pandas/datetime objects directly.
直接通过熊猫/ datetime对象。
>>> random_date(pd.datetime.now(), pd.datetime.now() + pd.offsets.Hour(3))
Timestamp('2014-03-06 14:51:16.035965', tz=None)
#7
5
Since Python 3 timedelta
supports multiplication with floats, so now you can do:
由于Python 3 timedelta支持浮点数的乘法,所以现在您可以这样做:
import random
random_date = start + (end - start) * random.random()
given that start
and end
are of the type datetime.datetime
. For example, to generate a random datetime within the next day:
给定的开始和结束都是类型datetime.datetime。例如,在第二天生成一个随机的datetime:
import random
from datetime import datetime, timedelta
start = datetime.now()
end = start + timedelta(days=1)
random_date = start + (end - start) * random.random()
#8
3
The easiest way of doing this is to convert both numbers to timestamps, then set these as the minimum and maximum bounds on a random number generator.
最简单的方法是将两个数字转换为时间戳,然后将它们设置为随机数生成器的最小和最大边界。
A quick PHP example would be:
一个简单的PHP例子是:
// Find a randomDate between $start_date and $end_date
function randomDate($start_date, $end_date)
{
// Convert to timetamps
$min = strtotime($start_date);
$max = strtotime($end_date);
// Generate random number using above bounds
$val = rand($min, $max);
// Convert back to desired date format
return date('Y-m-d H:i:s', $val);
}
This function makes use of strtotime()
to convert a datetime description into a Unix timestamp, and date()
to make a valid date out of the random timestamp which has been generated.
这个函数利用strtotime()将一个datetime描述转换为一个Unix时间戳,以及date(),以便从生成的随机时间戳中生成一个有效日期。
#9
3
You can Use Mixer
,
您可以使用搅拌机,
pip install mixer
and,
而且,
from mixer import generators as gen
print gen.get_datetime(min_datetime=(1900, 1, 1, 0, 0, 0), max_datetime=(2020, 12, 31, 23, 59, 59))
#10
2
Here is an answer to the literal meaning of the title rather than the body of this question:
这里是对标题的字面意思的回答,而不是这个问题的主体:
import time
import datetime
import random
def date_to_timestamp(d) :
return int(time.mktime(d.timetuple()))
def randomDate(start, end):
"""Get a random date between two dates"""
stime = date_to_timestamp(start)
etime = date_to_timestamp(end)
ptime = stime + random.random() * (etime - stime)
return datetime.date.fromtimestamp(ptime)
This code is based loosely on the accepted answer.
此代码松散地基于已接受的答案。
#11
2
Just to add another one:
再加一个:
datestring = datetime.datetime.strftime(datetime.datetime( \
random.randint(2000, 2015), \
random.randint(1, 12), \
random.randint(1, 28), \
random.randrange(23), \
random.randrange(59), \
random.randrange(59), \
random.randrange(1000000)), '%Y-%m-%d %H:%M:%S')
The day handling needs some considerations. With 28 you are on the secure site.
处理日常事务需要一些考虑。有28个你在安全的地方。
#12
1
- Convert your input dates to numbers (int, float, whatever is best for your usage)
- 将输入日期转换为数字(整数、浮点数、任何最适合您使用的)
- Choose a number between your two date numbers.
- 在两个日期之间选择一个数字。
- Convert this number back to a date.
- 将这个数字转换为日期。
Many algorithms for converting date to and from numbers are already available in many operating systems.
许多操作系统中已经有许多用于转换日期和数字的算法。
#13
1
What do you need the random number for? Usually (depending on the language) you can get the number of seconds/milliseconds from the Epoch from a date. So for a randomd date between startDate and endDate you could do:
你需要随机数来做什么?通常(取决于语言)您可以获得从一个日期开始的秒数/毫秒数。所以在startDate和endDate之间的随机日期可以做:
- compute the time in ms between startDate and endDate (endDate.toMilliseconds() - startDate.toMilliseconds())
- 计算startDate和endDate之间的时间(endDate.toMilliseconds() - startDate.toMilliseconds())
- generate a number between 0 and the number you obtained in 1
- 在0和你在1中得到的数字之间生成一个数字。
- generate a new Date with time offset = startDate.toMilliseconds() + number obtained in 2
- 生成一个新的日期,时间偏移= startDate.toMilliseconds() + 2中获得的数字。
#14
1
Here's a solution modified from emyller's approach which returns an array of random dates at any resolution
这是一个从emyller的方法修改的解决方案,它返回任意分辨率的随机日期数组。
import numpy as np
def random_dates(start, end, size=1, resolution='s'):
"""
Returns an array of random dates in the interval [start, end]. Valid
resolution arguments are numpy date/time units, as documented at:
https://docs.scipy.org/doc/numpy-dev/reference/arrays.datetime.html
"""
start, end = np.datetime64(start), np.datetime64(end)
delta = (end-start).astype('timedelta64[{}]'.format(resolution))
delta_mat = np.random.randint(0, delta.astype('int'), size)
return start + delta_mat.astype('timedelta64[{}]'.format(resolution))
Part of what's nice about this approach is that np.datetime64
is really good at coercing things to dates, so you can specify your start/end dates as strings, datetimes, pandas timestamps... pretty much anything will work.
这种方法的好处之一就是np。datetime64非常擅长于强制执行日期,所以您可以将开始/结束日期指定为字符串、datetimes、熊猫时间戳……几乎任何事情都可以。
#15
0
Conceptually it's quite simple. Depending on which language you're using you will be able to convert those dates into some reference 32 or 64 bit integer, typically representing seconds since epoch (1 January 1970) otherwise known as "Unix time" or milliseconds since some other arbitrary date. Simply generate a random 32 or 64 bit integer between those two values. This should be a one liner in any language.
在概念上很简单。根据您使用的语言,您将能够将这些日期转换为一些引用32或64位整数,通常表示自纪元(1970年1月1日)以来的秒数(1970年1月1日),也称为“Unix时间”,或自其他任意日期之后的毫秒数。在这两个值之间简单地生成一个32或64位整数。这应该是任何语言中的一行。
On some platforms you can generate a time as a double (date is the integer part, time is the fractional part is one implementation). The same principle applies except you're dealing with single or double precision floating point numbers ("floats" or "doubles" in C, Java and other languages). Subtract the difference, multiply by random number (0 <= r <= 1), add to start time and done.
在某些平台上,您可以生成一个时间为double(日期是整数部分,时间是小数部分是一个实现)。同样的原则适用于单或双精度浮点数(C、Java和其他语言中的“float”或“double”)。减去差异,乘以随机数(0 <= r <= 1),添加开始时间和完成。
#16
0
In python:
在python中:
>>> from dateutil.rrule import rrule, DAILY
>>> import datetime, random
>>> random.choice(
list(
rrule(DAILY,
dtstart=datetime.date(2009,8,21),
until=datetime.date(2010,10,12))
)
)
datetime.datetime(2010, 2, 1, 0, 0)
(need python dateutil
library – pip install python-dateutil
)
(需要python dateutil库- pip安装python-dateutil)
#17
0
Use ApacheCommonUtils to generate a random long within a given range, and then create Date out of that long.
使用ApacheCommonUtils在给定的范围内生成一个随机的长时间,然后创建日期。
Example:
例子:
import org.apache.commons.math.random.RandomData;
进口org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;
进口org.apache.commons.math.random.RandomDataImpl;
public Date nextDate(Date min, Date max) {
公开日期(日期、日期、日期、日期)
RandomData randomData = new RandomDataImpl();
return new Date(randomData.nextLong(min.getTime(), max.getTime()));
}
}
#18
0
I made this for another project using random and time. I used a general format from time you can view the documentation here for the first argument in strftime(). The second part is a random.randrange function. It returns an integer between the arguments. Change it to the ranges that match the strings you would like. You must have nice arguments in the tuple of the second arugment.
我用随机和时间做了另一个项目。我使用了一种通用格式,您可以在这里查看strftime()中的第一个参数的文档。第二部分是随机的。randrange函数。它在参数之间返回一个整数。将其更改为与您希望的字符串相匹配的范围。你必须在第二节课上有很好的论点。
import time
import random
def get_random_date():
return strftime("%Y-%m-%d %H:%M:%S",(random.randrange(2000,2016),random.randrange(1,12),
random.randrange(1,28),random.randrange(1,24),random.randrange(1,60),random.randrange(1,60),random.randrange(1,7),random.randrange(0,366),1))
#19
0
Pandas + numpy solution
熊猫+ numpy解决方案
import pandas as pd
import numpy as np
def RandomTimestamp(start, end):
dts = (end - start).total_seconds()
return start + pd.Timedelta(np.random.uniform(0, dts), 's')
dts is the difference between timestamps in seconds (float). It is then used to create a pandas timedelta between 0 and dts, that is added to the start timestamp.
dts是时间戳与秒之间的区别(float)。然后,它被用来在0到dts之间创建一个熊猫timedelta,它被添加到开始时间戳中。
#20
0
Based on the answer by mouviciel, here is a vectorized solution using numpy. Convert the start and end dates to ints, generate an array of random numbers between them, and convert the whole array back to dates.
基于mouviciel的答案,这里是一个使用numpy的矢量化解决方案。将开始和结束日期转换为ints,在它们之间生成一个随机数数组,并将整个数组转换为日期。
import time
import datetime
import numpy as np
n_rows = 10
start_time = "01/12/2011"
end_time = "05/08/2017"
date2int = lambda s: time.mktime(datetime.datetime.strptime(s,"%d/%m/%Y").timetuple())
int2date = lambda s: datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S')
start_time = date2int(start_time)
end_time = date2int(end_time)
random_ints = np.random.randint(low=start_time, high=end_time, size=(n_rows,1))
random_dates = np.apply_along_axis(int2date, 1, random_ints).reshape(n_rows,1)
print random_dates
#21
0
It's modified method of @(Tom Alsberg). I modified it to get date with milliseconds.
它修改了@(Tom Alsberg)的方法。我修改它以得到毫秒。
import random
import time
import datetime
def random_date(start_time_string, end_time_string, format_string, random_number):
"""
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.
"""
dt_start = datetime.datetime.strptime(start_time_string, format_string)
dt_end = datetime.datetime.strptime(end_time_string, format_string)
start_time = time.mktime(dt_start.timetuple()) + dt_start.microsecond / 1000000.0
end_time = time.mktime(dt_end.timetuple()) + dt_end.microsecond / 1000000.0
random_time = start_time + random_number * (end_time - start_time)
return datetime.datetime.fromtimestamp(random_time).strftime(format_string)
Example:
例子:
print TestData.TestData.random_date("2000/01/01 00:00:00.000000", "2049/12/31 23:59:59.999999", '%Y/%m/%d %H:%M:%S.%f', random.random())
Output: 2028/07/08 12:34:49.977963
输出:2028/07/08 12:34:49.977963
#22
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Create random datetime object."""
from datetime import datetime
import random
def create_random_datetime(from_date, to_date, rand_type='uniform'):
"""
Create random date within timeframe.
Parameters
----------
from_date : datetime object
to_date : datetime object
rand_type : {'uniform'}
Examples
--------
>>> random.seed(28041990)
>>> create_random_datetime(datetime(1990, 4, 28), datetime(2000, 12, 31))
datetime.datetime(1998, 12, 13, 23, 38, 0, 121628)
>>> create_random_datetime(datetime(1990, 4, 28), datetime(2000, 12, 31))
datetime.datetime(2000, 3, 19, 19, 24, 31, 193940)
"""
delta = to_date - from_date
if rand_type == 'uniform':
rand = random.random()
else:
raise NotImplementedError('Unknown random mode \'{}\''
.format(rand_type))
return from_date + rand * delta
if __name__ == '__main__':
import doctest
doctest.testmod()