Explain Codes LogoExplain Codes Logo

Print all day-dates between two dates

python
date-handling
generator-functions
list-comprehensions
Nikita BarsukovbyNikita Barsukov·Jan 19, 2025
TLDR

Leveraging datetime and timedelta functions from Python's datetime module, here's a precise code that iterates over a date range:

from datetime import datetime, timedelta start_date = datetime.strptime('YYYY-MM-DD', '%Y-%m-%d') # Replace with your Start date end_date = datetime.strptime('YYYY-MM-DD', '%Y-%m-%d') # Replace with your End date delta = timedelta(days=1) # Setting the interval for 1 day while start_date <= end_date: print(start_date.date()) # Prints the date and... Well, does nothing more :) start_date += delta # Start date on energy drink, jumping by a day each time

Replace 'YYYY-MM-DD' with your specific start and end dates to print all day-dates for the period.

Step-by-step to printing all day-dates

There's no such thing as too much date handling. Let's dissect the script, piece by piece, to fully grasp the concept:

Step 1: Initialization (Bringing the date to the party)

from datetime import datetime start_date = datetime.strptime('2023-01-01', '%Y-%m-%d') end_date = datetime.strptime('2023-01-31', '%Y-%m-%d')

Step 2: Picture a day (Or don't. We're just adding one to the current date)

from datetime import timedelta # Creating a day interval - treadmills for dates one_day = timedelta(days=1)

Step 3: Generator—Our own date yielder

def date_generator(start, end, step): while start <= end: # 'cause we don't like overshooting yield start # Hands out date on a silver platter start += step # Next date, please!

Generators are more memory-friendly, particularly over large ranges.

Step 4: Print it out (Or do some magic)

for single_date in date_generator(start_date, end_date, one_day): print(single_date.date().isoformat()) # ISO formatting because we aren't animals.

Note: Sit back and watch as .isoformat() transforms your output into a MMP (Machine and Man-friendly Print).

Create a list of all dates (Meet the List Comprehensions Squad)

Wondering how to skim all dates into a list? List comprehensions are here to save the day:

dates_list = [start_date + timedelta(days=n) for n in range((end_date - start_date).days + 1)] print([date.isoformat() for date in dates_list]) # Lock, Load and Print!

Compact, efficient and considerate towards the end date.

Fine-tuning for edge cases

Robust solutions factor in weirdness. Let's deal with some potential pain points.

Leap years and timezone-aware dates

Leap years and timezones can play spoilsport.

# Hey, it's Leap Year Detection Squad import calendar year = 2024 # A wild leap year appears print(calendar.isleap(year)) # Outputs: True # Timezone aware start and end dates from datetime import timezone import pytz start_date = start_date.replace(tzinfo=pytz.UTC) end_date = end_date.replace(tzinfo=timezone.utc) # UTC for consistency

New Year's rollover

The algorithm shan't be puzzled if dates span multiple years.

start_date = datetime.strptime('2022-12-31', '%Y-%m-%d') end_date = datetime.strptime('2023-01-02', '%Y-%m-%d') # We party on New Year’s Eve!