Generating random dates within a given range in pandas

  • A+
Category:Languages

This is a self-answered post. A common problem is to randomly generate dates between a given start and end date.

For example, given some start date 2015-01-01 and an end date 2018-01-01, how can I sample N random dates between this range using pandas?

There are two cases to consider:

  1. random dates with a time component, and
  2. random dates without time

I explain how both can be achieved below in a handful of lines of code.

 


Is converting to the unix timestamp acceptable?

def random_dates(start, end, n=10):      start_u = start.value//10**9     end_u = end.value//10**9      return pd.to_datetime(np.random.randint(start_u, end_u, n), unit='s') 

Sample run:

start = pd.to_datetime('2015-01-01') end = pd.to_datetime('2018-01-01') random_dates(start, end)  DatetimeIndex(['2016-10-08 07:34:13', '2015-11-15 06:12:48',                '2015-01-24 10:11:04', '2015-03-26 16:23:53',                '2017-04-01 00:38:21', '2015-05-15 03:47:54',                '2015-06-24 07:32:32', '2015-11-10 20:39:36',                '2016-07-25 05:48:09', '2015-03-19 16:05:19'],               dtype='datetime64[ns]', freq=None) 

EDIT:

As per the comment by @smci, I wrote a function to accommodate both 1 and 2 with a little explanation inside the function itself.

def random_datetimes_or_dates(start, end, out_format='datetime', n=10):       '''        unix timestamp is in ns by default.      I divide the unix time value by 10**9 to make it seconds (or 24*60*60*10**9 to make it days).     The corresponding unit variable is passed to the pd.to_datetime function.      Values for the (divide_by, unit) pair to select is defined by the out_format parameter.     for 1 -> out_format='datetime'     for 2 -> out_format=anything else     '''     (divide_by, unit) = (10**9, 's') if out_format=='datetime' else (24*60*60*10**9, 'D')      start_u = start.value//divide_by     end_u = end.value//divide_by      return pd.to_datetime(np.random.randint(start_u, end_u, n), unit=unit)  

Sample run:

random_datetimes_or_dates(start, end, out_format='datetime')  DatetimeIndex(['2017-01-30 05:14:27', '2016-10-18 21:17:16',                '2016-10-20 08:38:02', '2015-09-02 00:03:08',                '2015-06-04 02:38:12', '2016-02-19 05:22:01',                     '2015-11-06 10:37:10', '2017-12-17 03:26:02',                    '2017-11-20 06:51:32', '2016-01-02 02:48:03'],                   dtype='datetime64[ns]', freq=None)  random_datetimes_or_dates(start, end, out_format='not datetime')  DatetimeIndex(['2017-05-10', '2017-12-31', '2017-11-10', '2015-05-02',                '2016-04-11', '2015-11-27', '2015-03-29', '2017-05-21',                '2015-05-11', '2017-02-08'],               dtype='datetime64[ns]', freq=None) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: