A2oz

How to Get the Yesterday Date in Python?

Published in Python Date and Time 2 mins read

You can easily obtain yesterday's date in Python using the datetime module. Here's how:

Using datetime.timedelta

  1. Import the datetime module:

    import datetime
  2. Get today's date:

    today = datetime.date.today()
  3. Subtract one day using timedelta:

    yesterday = today - datetime.timedelta(days=1)
  4. Print the result:

    print(yesterday)

Example:

import datetime

today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
print(yesterday)

This code will output yesterday's date in the format YYYY-MM-DD.

Using date.fromordinal

Another approach is to use the date.fromordinal method:

  1. Import the datetime module:

    import datetime
  2. Get today's date:

    today = datetime.date.today()
  3. Calculate yesterday's ordinal:

    yesterday_ordinal = today.toordinal() - 1
  4. Convert the ordinal to a date:

    yesterday = datetime.date.fromordinal(yesterday_ordinal)
  5. Print the result:

    print(yesterday)

Example:

import datetime

today = datetime.date.today()
yesterday_ordinal = today.toordinal() - 1
yesterday = datetime.date.fromordinal(yesterday_ordinal)
print(yesterday)

This method also outputs yesterday's date in the format YYYY-MM-DD.

Both methods achieve the same outcome, providing you with a way to retrieve yesterday's date in your Python code.

Related Articles