How can I generate a random HH:MM:SS
time using datetime
?
I get just 00:00:00
everytime
import datetime
print(datetime.time())
>>> 00:00:00
CodePudding user response:
Try this:
import random
from datetime import datetime, timedelta
min_year=1900
max_year=datetime.now().year
start = datetime(min_year, 1, 1, 00, 00, 00)
years = max_year - min_year 1
end = start timedelta(days=365 * years)
for i in range(10):
random_date = start (end - start) * random.random()
print(random_date)
#done
# or a function
def gen_datetime(min_year=1900, max_year=datetime.now().year):
# generate a datetime in format yyyy-mm-dd hh:mm:ss.000000
start = datetime(min_year, 1, 1, 00, 00, 00)
years = max_year - min_year 1
end = start timedelta(days=365 * years)
return start (end - start) * random.random()
from https://gist.github.com/rg3915/db907d7455a4949dbe69
CodePudding user response:
Simplest answer I could think of. Thanks @deceze for inspiration.
import datetime
import random
print(datetime.time(hour=random.randint(0, 23), minute=random.randint(0, 59), second=random.randint(0, 59)))