Explain Codes LogoExplain Codes Logo

Generate a random date between two other dates

python
date-formatting
faker
datetime
Anton ShumikhinbyAnton Shumikhin·Jan 8, 2025
TLDR

Generate a random date calculating the difference between your start and end dates, then adding a randomly chosen sequence of days to your start date. It's all about applying magic from datetime.timedelta:

import random from datetime import datetime, timedelta start_date = datetime(2020, 1, 1) # Starting from New Year's eve. Neat huh? end_date = datetime(2021, 1, 1) # Not a time traveler yet; staying within this year random_date = start_date + timedelta(days=random.randint(0, (end_date - start_date).days)) print(random_date) # It's Date'o'clock!

This script masterfully generates a random_date within the specified date range by utilizing random.randint for selecting a random day and timedelta to glue it all together.

Time is ticking: Introducing precision

Shortening or lengthening the timeline is all about precise control. Let's dial up precision to the second:

random_second = random.randint(0, int((end_date - start_date).total_seconds())) # Seconds...ticking away random_date = start_date + timedelta(seconds=random_second) print(random_date) # Don't blink! You might miss it

Here we call total_seconds() to compute the total duration in seconds and punch in random.randint to pick an exact second.

Leap Year: An extra day of fun

Leap years add a twist with their extra day on February 29th. Gotta count those!

year = start_date.year leap_days = sum(1 for y in range(year, end_date.year + 1) if (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)) # Watch your leap! total_days = (end_date - start_date).days + leap_days

Leap_days make sure our random date generator doesn't skip the extra day of fun during leap years!

Faker or Radar: Pick your weapon

For random but convincing dates, modules like Faker or radar are a saving grace:

from faker import Faker fake = Faker() random_date = fake.date_between(start_date='-30y', end_date='today') # Never mind my 30-year long existential crisis print(random_date) # Welcome to the past...or future

Faker provides an arsenal of randomizers with just a few simple commands.

Different strokes for different folks: Varying time formats

It's crucial to embrace the diversity of date formats:

from datetime import datetime date_string = "01-31-2020 14:45:37" # Because why not? date_format = "%m-%d-%Y %H:%M:%S" # The secret lay in the format # Convert string to datetime converted_date = datetime.strptime(date_string, date_format) print(converted_date) # Hurray! We can read date in human language now

Learning different formats adds robustness and prevents mishaps caused by minor irregularities in data inputs.

Unix to the rescue: Switching time formats

Working with Unix time? Switching between Unix time and human-readable dates is as smooth as butter:

import time unix_timestamp = time.mktime(time.strptime(date_string, date_format)) # *Beep Boop* says the Unix machine print(unix_timestamp) human_readable_date = datetime.fromtimestamp(unix_timestamp) print(human_readable_date) # And we're back to English again!

Formatting the outcome

After making dates dance, your output might need a certain swag. Use strftime:

formatted_date = random_date.strftime("%A, %B %d, %Y %I:%M:%S %p") print(formatted_date) # Dressed to impress!

This changes our random_date from a boring string to an elegant, readable format.