Generate Random Times in Python
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: Python
What: Generate random times in Python using random.randint() and datetime.time. Covers 12-hour, 24-hour formats, and time validation.
Try it: Use our interactive Times generator or integrate this code into your Python application.
Generate random times in Python using random.randint() and datetime.time. Covers 12-hour, 24-hour formats, and time validation. Looking for other languages? Check our code examples in PHP , JavaScript , Java , C# , C++ , Ruby and Go or use our interactive web generator.
Python Code Example
import random
from datetime import time
# Generate random time (24-hour format HH:MM:SS)
def random_time_24():
hour = random.randint(0, 23)
minute = random.randint(0, 59)
second = random.randint(0, 59)
return f"{hour:02d}:{minute:02d}:{second:02d}"
# Generate random time (12-hour format with AM/PM)
def random_time_12():
hour = random.randint(1, 12)
minute = random.randint(0, 59)
ampm = random.choice(["AM", "PM"])
return f"{hour:02d}:{minute:02d} {ampm}"
# Generate random time within business hours (9 AM - 5 PM)
def random_business_time():
hour = random.randint(9, 17)
minute = random.randint(0, 59)
return f"{hour:02d}:{minute:02d}"
# Generate random time as datetime.time object
def random_time_object():
return time(
hour=random.randint(0, 23),
minute=random.randint(0, 59),
second=random.randint(0, 59)
)
# Validate time format (HH:MM:SS)
def is_valid_time(time_str):
import re
pattern = r"^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$"
return re.match(pattern, time_str) is not None
# Generate multiple random times
def generate_times(count=10):
return [random_time_24() for _ in range(count)]
print(f"24-hour: {random_time_24()}")
print(f"12-hour: {random_time_12()}")
print(f"Business: {random_business_time()}")
print(f"Time object: {random_time_object()}")
print(f"Valid: {is_valid_time('14:30:45')}")
print(f"Batch: {\", \".join(generate_times(3))}")
[EXPLANATION]
Python uses random.randint() for hours (0-23), minutes (0-59), and seconds (0-59). F-string formatting with :02d adds leading zeros. datetime.time creates time objects with hour, minute, second parameters. random.choice() selects AM/PM. re.match() validates format. List comprehensions provide concise batch generation. Time objects are independent of dates.
Expected Output
24-hour: 14:23:45 12-hour: 09:15 AM Business: 11:30 Time object: 14:23:45 Valid: True Batch: 08:45:12, 16:20:33, 22:10:05
Common Use Cases
- Generate times for Django/Flask scheduling tests
- Create time fields for SQLAlchemy model testing
- Generate working hours for employee management
- Test time validation in web applications
- Create appointment times for booking systems
Important Notes
-
F-string
f"{hour:02d}"formats with leading zeros -
datetime.timeis timezone-naive by default -
strftime()formats time objects:time_obj.strftime("%H:%M") -
random.choice()randomly selects from list items -
Use
datetime.datetime.combine()to add date to time
Try Our Interactive Generator
Don't want to write code? Use our free web-based Times generator with instant results.
TRY TIMES GENERATOR →Other Programming Languages
View Times generation code examples in PHP
View Times generation code examples in JavaScript
View Times generation code examples in Java
View Times generation code examples in C#
View Times generation code examples in C++
View Times generation code examples in Ruby
View Times generation code examples in Go