user9394674
user9394674

Reputation:

Generate random list of timestamps in python

I'm trying to generate random list of 24hr timestamps. I can generate one sample of date and time between the set range using the code below. I'm hoping to generate multiple samples (e.g. 10 samples)

Also, the date component isn't a priority for me. If i could drop that and just generate random 24hr timestamps that would be good.

Most threads I've found only consider generate random dates. I can find anything that concerns time.

import random
import time
from datetime import datetime

def randomDate(start, end):
    frmt = '%d-%m-%Y %H:%M:%S'

    stime = time.mktime(time.strptime(start, frmt))
    etime = time.mktime(time.strptime(end, frmt))

    ptime = stime + random.random() * (etime - stime)
    dt = datetime.fromtimestamp(time.mktime(time.localtime(ptime)))
    return dt

random_datetime = randomDate("20-01-2018 13:30:00", "23-01-2018 04:50:34")

print(random_datetime)

Output:

2018-01-21 03:33:55

Upvotes: 5

Views: 20970

Answers (4)

abarnert
abarnert

Reputation: 365657

The whole point of the datetime library: datetime, timedelta, etc. objects act as much like numbers as possible, so you can just do arithmetic on them.

So, to generate a uniform distribution over a day, just take a uniform distribution from 0.0 to 1.0, and multiply it by a day:1

td = random.random() * datetime.timedelta(days=1)

To generate a uniform random time on some particular day, just add that to midnight on that day:

dt = datetime.datetime(2018, 5, 1) + random.random() * datetime.timedelta(days=1)

To generate a random timestamp between two timestamps:

dt = random.random() * (end - start) + start

And if you want 10 of those:

[random.random() * (end - start) + start for _ in range(10)]

That's all there is to it. Stay away from all those other time formats from the time module; they're only needed if you need compatibility with stuff like C libraries and filesystem data. Just use datetime in the first place:

def randomtimes(start, end, n):
    frmt = '%d-%m-%Y %H:%M:%S'
    stime = datetime.datetime.strptime(start, frmt)
    etime = datetime.datetime.strptime(end, frmt)
    td = etime - stime
    return [random.random() * td + stime for _ in range(n)]

1. However, keep in mind that if you're dealing with local rather than UTC times, some days are actually 23 or 25 hours long, because of Daylight Saving Time. A timedelta doesn't understand that.

Upvotes: 15

bfris
bfris

Reputation: 5805

Depending on your needs, it might be well worth the trouble to learn the Python datetime and time modules. If your code will do lots of different manipulations, then go with @abarnert's answer. If all you need is a time string (rather than a Python timestamp), this function will crank it out for you:

import random

def randomTime():
    # generate random number scaled to number of seconds in a day
    # (24*60*60) = 86,400
    
    rtime = int(random.random()*86400)
    
    hours   = int(rtime/3600)
    minutes = int((rtime - hours*3600)/60)
    seconds = rtime - hours*3600 - minutes*60
    
    time_string = '%02d:%02d:%02d' % (hours, minutes, seconds)
    return time_string
    
for i in range(10):
    print(randomTime())

this outputs:

19:07:31
16:32:00
02:01:30
20:31:21
20:20:26
09:49:12
19:38:42
10:49:32
13:13:36
15:02:54

But if you don't want 24 hour time, then you can intercept the 'hours' variable before you stuff it in into the string:

import random

def randomTime():
    # generate random number scaled to number of seconds in a day
    # (24*60*60) = 86,400
    
    rtime = int(random.random()*86400)
    
    hours   = int(rtime/3600)
    minutes = int((rtime - hours*3600)/60)
    seconds = rtime - hours*3600 - minutes*60
    
    # figure out AM or PM
    if hours >= 12:
        suffix = 'PM'
        if hours > 12:
            hours = hours - 12
    else:
        suffix = 'AM'
    
    time_string = '%02d:%02d:%02d' % (hours, minutes, seconds)
    time_string += ' ' + suffix
    return time_string
    
for i in range(10):
    print(randomTime())

which gives :

05:11:45 PM
02:28:44 PM
08:09:19 PM
02:52:30 PM
07:40:02 PM
03:55:16 PM
03:48:44 AM
12:35:43 PM
01:32:51 PM
07:54:26 PM

Upvotes: 4

Rene Montesardo
Rene Montesardo

Reputation: 51

In case you need continuous times:

from datetime import datetime,timedelta

time_starter = datetime.strptime("12:00:00","%H:%M:%S")

for i in range(1,10):
    time = time_starter + timedelta(hours=i)
    time = time.strftime("%H:%M:%S")

    print(time)

if you need random or continuous minutes use:

time = time_starter + timedelta(minutes=i) #continuous 
time = time_starter + timedelta(minutes=randint(0,60)) #random

Upvotes: 1

Shrey Sharma
Shrey Sharma

Reputation: 63

import random
import time
from datetime import datetime
dates = []
def randomDate(start, end):
    frmt = '%d-%m-%Y %H:%M:%S'

    stime = time.mktime(time.strptime(start, frmt))
    etime = time.mktime(time.strptime(end, frmt))

    ptime = stime + random.random() * (etime - stime)
    dt = datetime.fromtimestamp(time.mktime(time.localtime(ptime)))
    return dt

for i in range(0 , 10)
    dates.append(randomDate("20-01-2018 13:30:00", "23-01-2018 04:50:34"))

Your dates will have a list of 10 sample date :)
Good Luck

Upvotes: 0

Related Questions