Return a random time between two times

Viewed 261

I have some trouble with a code in Python. I'm supposed to create a code that generates a random time between 08:00:00 and 20:59:59 and my function should return a time object. I have to use the modules random and datetime. So far i've tried this:

import random
import datetime
def random_time(start, end):
    start = datetime.time(9, 0, 0)
    end = datetime.time(21, 59, 59)
    a = random.random(start, end)
    return a

When I try this it says that "start" is not defined. Am I at least on the right track? :)

2 Answers

I would go for timedelta and seconds as integers (via timedelta.totalseconds(), something like this:

import random
import datetime

start = datetime.timedelta(hours=9, minutes=0, seconds=0)
end = datetime.timedelta(hours=21, minutes=59, seconds=59)

random_seconds=random.randint(start.total_seconds(),end.total_seconds())

random_time=datetime.timedelta(seconds=random_seconds)

print(random_time)

As mentioned in first answer it's better to use timedelta for your task.

And you don't have to reinitialise your start and end parameters inside function. For example:

from random import randrange
from datetime import timedelta


def random_time(start, end):
    return timedelta(seconds=randrange(timedelta(hours=start).total_seconds(),
                                       timedelta(hours=end).total_seconds()))


print(random_time(9, 22))

Related