Explain Codes LogoExplain Codes Logo

How to subtract a day from a date?

python
datetime-module
dateutil-realtivedelta
pendulum-library
Nikita BarsukovbyNikita Barsukov·Dec 29, 2024
TLDR

Sure-fire choice: Use Python's datetime.timedelta to subtract 1 day from a datetime.date or datetime.datetime object. Here's how:

from datetime import datetime, timedelta # You'd better remember the Ides of March... new_date = datetime(2023, 3, 15) - timedelta(1) print(new_date) # -> 2023-03-14, Et tu, Brute?

Time zones and daylight saving

Earth isn't flat, mind time zones! We live in a time of global reach. If your application crosses the borders, consider tzinfo from the datetime module, or better yet, third-party libraries like pytz or pendulum.

Keeping time: subtracting a day in 'US/Eastern':

import pytz from datetime import datetime, timedelta # "What's today?" "Why, it's Christmas day, sir!" today = datetime.now(pytz.timezone('US/Eastern')) # Subtract a day whilst saying "Bah, humbug!" to DST and time zone errors yesterday = today - timedelta(days=1) yesterday = yesterday.astimezone(pytz.timezone('US/Eastern')) print(yesterday) # Ebenezer Scrooge approves.

Going granular with relativedelta

Crying over spilt seconds? When every millisecond counts, dateutil.relativedelta offers precision for custom time calculations.

Subtracting a day, end-of-the-month headaches notwithstanding:

from datetime import datetime from dateutil.relativedelta import relativedelta # "Be kind whenever possible. It is always possible." today = datetime.now() yesterday = today - relativedelta(days=1) print(yesterday) # Yesterday brought the beginning, tomorrow brings the end.

Winning reliability points

How to not lose at date manipulation:

  • Don't play hide and seek: Always handle time zones explicitly.
  • If you're picky with your time zones, go for tzlocal.get_localzone to get by.
  • Time travelling? Research the DST rules for historical dates.

Advanced cases

A date with pendulum

Pendulum to the rescue: no more DST and timezone adjustments.

import pendulum today = pendulum.now('US/Eastern') # Bye to today, hello yesterday! yesterday = today.subtract(days=1) print(yesterday)

Negative timedelta for the win

Just because we can't turn back time (except in songs ⏪🎵), doesn't mean our code can't!

# Who said we can't time travel? Back to the future! last_week = today + timedelta(weeks=-1) print(last_week) # Marty McFly: "Whoa, this is heavy."

Chasing the masses

Top-voted and accepted Stack Overflow answers are your treasure maps to the most effective solutions. Unearth these gems for practical and tried-and-true codes.