生成numpy范围内的随机日期

Sir*_* S. 6 python arrays datetime numpy pandas

如何在双月的基础上在一系列日期内生成随机日期numpy?我能想到的一种方法是生成两组随机整数数组:

bimonthly1 = np.random.randint(1,15,12)
bimonthly2 = np.random.randint(16,30,12)
Run Code Online (Sandbox Code Playgroud)

然后,我可以生成日期,每个月使用上述两个数组的"日期"值.但是,这将要求我明确传递月份和年份数据.一种解决方案是生成所需的date_range第一个并用上述数组值替换该范围内的"天".但对于大型阵列,这可能不是最好的解决方案.此方法需要对范围的每个元素进行操作.

我将非常感谢有关如何numpy更有效地执行此操作的任何指示.

小智 6

有一种更简单的方法可以实现此目的,而无需显式调用numpy以外的任何库。

Numpy具有非常强大的datetime数据类型:特别是在这种情况下,您可以加减整数,并将其视为可用的最小时间单位。例如,对于%Y-%m-%d格式:

exampledatetime1 = np.datetime64('2017-01-01')
exampledatetime1 + 1
>>
2017-01-02
Run Code Online (Sandbox Code Playgroud)

但是,对于%Y-%m-%d%H:%M:%S格式:

exampledatetime2 = np.datetime64('2017-01-01 00:00:00')
exampledatetime2 + 1
>>
2017-01-01 00:00:01
Run Code Online (Sandbox Code Playgroud)

在这种情况下,由于您只有一天的时间才能获得信息,因此您只需执行以下操作:

import numpy as np

bimonthly_days = np.arange(0, 60)
base_date = np.datetime64('2017-01-01')
random_date = base_date + np.random.choice(bimonthly_days)
Run Code Online (Sandbox Code Playgroud)

或者,如果您想对此更加清洁:

import numpy as np

def random_date_generator(start_date, range_in_days):
    days_to_add = np.arange(0, range_in_days)
    random_date = np.datetime64(start_date) + np.random.choice(days_to_add)
    return random_date
Run Code Online (Sandbox Code Playgroud)

然后只需使用:

yourdate = random_date_generator('2012-01-15', 60)
Run Code Online (Sandbox Code Playgroud)