How to subtract a day from a date?
Sure-fire choice: Use Python's datetime.timedelta to subtract 1 day from a datetime.date or datetime.datetime object. Here's how:
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':
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:
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_localzoneto 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.
Negative timedelta for the win
Just because we can't turn back time (except in songs ⏪🎵), doesn't mean our code can't!
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.
Was this article helpful?