Developer Tools for Random Data Generation // v2.6.1
root@generate-random:~/dates/python$ _

Generate Random Dates in Python

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: Python

What: Generate random dates in Python using datetime and Faker library. Covers date ranges, timedelta, formatting, timezone handling, and realistic test data generation.

Try it: Use our interactive Dates generator or integrate this code into your Python application.

Generate random dates in Python using datetime and Faker library. Covers date ranges, timedelta, formatting, timezone handling, and realistic test data generation. 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 datetime, timedelta

# Generate random date between two dates
def random_date(start_date, end_date):
    start = datetime.strptime(start_date, "%Y-%m-%d")
    end = datetime.strptime(end_date, "%Y-%m-%d")
    delta = end - start
    random_days = random.randint(0, delta.days)
    return start + timedelta(days=random_days)

# Generate random past date (within last N days)
def random_past_date(days_ago=365):
    today = datetime.now()
    past = today - timedelta(days=random.randint(0, days_ago))
    return past

# Generate random future date (within next N days)
def random_future_date(days_ahead=365):
    today = datetime.now()
    future = today + timedelta(days=random.randint(0, days_ahead))
    return future

# Generate random birthday (18-80 years ago)
def random_birthday():
    today = datetime.now()
    min_age = 18
    max_age = 80
    years_ago = random.randint(min_age, max_age)
    birth_year = today.year - years_ago
    return random_date(f"{birth_year}-01-01", f"{birth_year}-12-31")

# Generate random datetime with time component
def random_datetime(start_date, end_date):
    date = random_date(start_date, end_date)
    random_hour = random.randint(0, 23)
    random_minute = random.randint(0, 59)
    random_second = random.randint(0, 59)
    return datetime(date.year, date.month, date.day,
                   random_hour, random_minute, random_second)

# Generate multiple random dates
def generate_random_dates(count=10, start_date="2020-01-01", end_date="2025-12-31"):
    return [random_date(start_date, end_date).strftime("%Y-%m-%d")
            for _ in range(count)]

# Using Faker library (install: pip install faker)
# from faker import Faker
# fake = Faker()
# random_date = fake.date_between(start_date="-1y", end_date="today")
# past_date = fake.past_date(start_date="-30d")
# future_date = fake.future_date(end_date="+90d")
# birthday = fake.date_of_birth(minimum_age=18, maximum_age=80)
# datetime_obj = fake.date_time_between(start_date="-1y", end_date="now")

# Usage examples
print("Random date:", random_date("2020-01-01", "2025-12-31").strftime("%Y-%m-%d"))
print("Past date:", random_past_date(30).strftime("%Y-%m-%d"))
print("Future date:", random_future_date(90).strftime("%Y-%m-%d"))
print("Random birthday:", random_birthday().strftime("%Y-%m-%d"))
print("With time:", random_datetime("2024-01-01", "2024-12-31").strftime("%Y-%m-%d %H:%M:%S"))
print("Batch:", generate_random_dates(5))

[EXPLANATION]

Python's datetime module provides date/time handling. strptime() parses strings to datetime objects, strftime() formats them. timedelta represents time differences for date arithmetic. The Faker library offers date_between(), past_date(), future_date(), and date_of_birth() with intuitive parameters. Format codes: %Y (year), %m (month), %d (day), %H (hour), %M (minute), %S (second). For timezone support, use pytz or built-in timezone.

Expected Output

Random date: 2023-07-15
Past date: 2024-11-17
Future date: 2025-03-15
Random birthday: 1985-04-23
With time: 2024-07-15 14:32:47
Batch: ["2022-03-12", "2024-08-05", "2021-11-28", "2023-05-19", "2025-01-07"]

Common Use Cases

  • Generate test data for Django/Flask user models with timestamps
  • Create sample event data for data science and analytics
  • Populate pandas DataFrames with realistic date columns
  • Test date-based filtering in database queries
  • Generate time-series data for machine learning models

Important Notes

  • datetime.now() returns current local time; use datetime.utcnow() for UTC
  • timedelta supports days, seconds, microseconds, milliseconds, minutes, hours, weeks
  • Faker's date_between() accepts relative strings like "-1y", "+30d", "today"
  • For timezone-aware dates, use datetime.now(tz=timezone.utc)
  • strftime() and strptime() use same format codes for consistency

Try Our Interactive Generator

Don't want to write code? Use our free web-based Dates generator with instant results.

TRY DATES GENERATOR →