Explain Codes LogoExplain Codes Logo

Creating a range of dates in Python

python
dateutil
pandas
datetime
Anton ShumikhinbyAnton Shumikhin·Sep 11, 2024
TLDR

For a quick solution, pandas' date_range() function does the job:

import pandas as pd dates = pd.date_range('2021-01-01', periods=10) print(dates)

This code creates a sequence of dates starting from January 1, 2021, for 10 days. The output is a DatetimeIndex, ready to be used in any time-series operations.

Control over your dates with datetime and timedelta

One-liner solution for date range

Opt for Python's built-in datetime and timedelta if you need more customization:

from datetime import datetime, timedelta def generate_dates(start_date, end_date): return [(start_date + timedelta(days=i)).isoformat() for i in range((end_date - start_date).days + 1)] start_date = datetime.strptime('2021-01-01', '%Y-%m-%d') end_date = datetime.strptime('2021-01-10', '%Y-%m-%d') dates_list = generate_dates(start_date, end_date) print(dates_list)

Here, list comprehension works hard to push dates into our list, one day at a time.

Pythonic way for memory efficiency

If the range is too big, a generator keeps the memory use minimal:

def date_generator(start_date, end_date): current_date = start_date while current_date <= end_date: yield current_date current_date += timedelta(days=1) for single_date in date_generator(start_date, end_date): print(single_date.isoformat())

Now, we're saving memory while we time travel. 🚀

Taming large ranges with islice

itertools.islice can handle gargantuan date ranges without breaking a sweat:

import itertools large_range = itertools.islice(date_generator(start_date, end_date), 1000)

This will efficiently handle the first 1000 dates only, and memory won't even notice it.

Optimizing date range creation

Using Python's dateutil for complex ranges

The python-dateutil package has got your back for complex date recurrences:

from dateutil.rrule import rrule, DAILY dates_range = list(rrule(DAILY, dtstart=start_date, until=end_date))

'cause sometimes we need to be complex, right? 🧙‍♂️

Convert pandas Timestamps to Python datetimes

To convert pandas Timestamps to Pythonic datetime objects, «voilà!»:

py_dates = [d.to_pydatetime() for d in pd.date_range(start_date, end_date)]

Converted them just like that! 🔁

Time zones? pandas got your back

Working with date ranges across time zones? No problem, pandas has got you covered:

tz_dates = pd.date_range(start_date, periods=10, tz='UTC') print(tz_dates)

Yeah, cross-timezone relationships are no more complicated! ⌚✈️

Fun with NumPy: dates and speed

NumPy's datetime for speed

If you fancy NumPy and need speed, use datetime64:

import numpy as np np_dates = np.arange('2021-01-01', '2021-01-11', dtype='datetime64[D]') print(np_dates)

There you go, 0 to 60 dates in no time! 🏁