Python Tutorial (33) – Example: Get yesterday's date

Time: Column:Python views:310

Python Code to Get Yesterday's Date Using the datetime Module

The following Python code demonstrates how to use the datetime module to get the date for yesterday.

Example: Get Yesterday's Date

# Import the datetime module
import datetime

def getYesterday(): 
    # Get today's date
    today = datetime.date.today()
    
    # Define a time delta of one day
    oneday = datetime.timedelta(days=1)
    
    # Calculate yesterday's date
    yesterday = today - oneday
    
    return yesterday

# Output
print(getYesterday())

Sample Output:

2024-09-10

Explanation:

  • The output indicates that yesterday's date is September 10, 2024.

This code helps you easily determine the date for the previous day using Python's datetime module.