Explain Codes LogoExplain Codes Logo

Formatting "yesterday's" date in Python

python
date-formatting
datetime
python-2-compatibility
Nikita BarsukovbyNikita Barsukov·Feb 7, 2025
TLDR

Let's knead some Python to get yesterday's date:

from datetime import datetime, timedelta print((datetime.now() - timedelta(1)).strftime('%Y-%m-%d'))

This slices up yesterday's date as YYYY-MM-DD.

Dealing with various date formats

Yummy! However, different formats are sometimes required. Let's present yesterday's date like MM-DD-YY:

yesterday_format_mmddyy = (datetime.now() - timedelta(days=1)).strftime('%m-%d-%y') # Hot from the oven! print(yesterday_format_mmddyy)

This presents yesterday's date as MM-DD-YY. Note the %y, it's a mini-chameleon, it changes to last two digits of the year. If you need the full year, use %Y instead.

Python datetime is a calendar masterchef! Leap years? Varying lengths of months? All catered for when we serve yesterday's date.

Python 2 compatibility

Oldie but a goodie, Python 2 is still around! Here's the recipe for it:

from datetime import datetime, timedelta yesterday = datetime.now() - timedelta(days=1) print yesterday.strftime('%Y-%m-%d') # Sans parentheses print, lived happily ever after

Going beyond: Efficient management of yesterday’s date

Great! You can retrieve yesterday's date now, but let's roll some more dough and understand how to manage and utilize it.

Working with time zones

Geography matters in cooking and coding. Time zones can affect date calculations. Whip out pytz or dateutil to ensure you’re on time.

Date comparisons

Comparing yesterday's date with another date? Simply whip out your trusty comparison operators (like ==, <, >). Operator for the win!

Parsing strings back to dates

Got a date in string and need to turn it into a datetime object? No problemo! Reach for datetime.strptime:

from datetime import datetime date_string = "04-05-23" date_object = datetime.strptime(date_string, '%m-%d-%y') # Wrapping secret ingredients back to original format

Serialization

Cookies anyone? When sending dates between systems or storing them, serialization really matters. Convert to strings or use ISO 8601 format with datetime.isoformat(). Delightfully interoperable!