Skip to content
Advertisement

Generate list of random datetimes in ISO8601 format in Python

I want to generate a list of length n with random datetime strings in Python within a range.

import datetime
start = datetime.datetime(2019,1,1,0,0,0).astimezone().replace(microsecond=0).isoformat()
end = datetime.datetime(2019,12,31,23,59,59).astimezone().replace(microsecond=0).isoformat()

I had asked a similar question before, but I did not use the correct format for datetime.What is the best way to achieve this?

Advertisement

Answer

Modifying the answer here for your format: https://stackoverflow.com/a/553448/7942856

from random import randrange
from datetime import timedelta, datetime

start = datetime(2019,1,1,0,0,0).astimezone().replace(microsecond=0)
end = datetime(2019,12,31,23,59,59).astimezone().replace(microsecond=0)

n = 5

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)

random_dates = [random_date(start, end) for i in range(n)]

Outputs:

[datetime.datetime(2019, 8, 6, 2, 25, 32, tzinfo=datetime.timezone(datetime.timedelta(seconds=39600), 'AUS Eastern Summer Time')), datetime.datetime(2019, 8, 5, 13, 2, 15, tzinfo=datetime.timezone(datetime.timedelta(seconds=39600), 'AUS Eastern Summer Time')), datetime.datetime(2019, 6, 24, 15, 57, 19, tzinfo=datetime.timezone(datetime.timedelta(seconds=39600), 'AUS Eastern Summer Time')), datetime.datetime(2019, 5, 3, 9, 35, 8, tzinfo=datetime.timezone(datetime.timedelta(seconds=39600), 'AUS Eastern Summer Time')), datetime.datetime(2019, 2, 12, 14, 33, 35, tzinfo=datetime.timezone(datetime.timedelta(seconds=39600), 'AUS Eastern Summer Time'))]

Then if you want the text ISO format, simply call .isoformat() on your list elements.

[random_date(start, end).isoformat() for i in range(n)]
#['2019-05-03T22:06:56+11:00', '2019-12-31T06:56:09+11:00', '2019-03-09T05:07:59+11:00', '2019-03-24T09:24:42+11:00', '2019-01-08T03:23:31+11:00']
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement