0

I want a code snippet that give today's date and yesterday's date in YYYY-MM-DD format. I know how to extract the current date and here is the code for it:

import datetime
cur_date = datetime.datetime.today().strftime('%Y-%m-%d')

But I do not know how to extract the previous day's date. Is manipulating the current date the only method to do so?

Siddhesh Agarwal
  • 159
  • 1
  • 12
  • 1
    Does this answer your question? [Python - Get Yesterday's date as a string in YYYY-MM-DD format](https://stackoverflow.com/questions/30483977/python-get-yesterdays-date-as-a-string-in-yyyy-mm-dd-format) – Pranav Hosangadi Jan 27 '21 at 14:59
  • 1
    For reference [documentation](https://docs.python.org/3/library/datetime.html#datetime.timedelta) – Girish Jan 27 '21 at 15:00
  • 1
    [How much research effort is expected of Stack Overflow users?](//meta.stackoverflow.com/a/261593/843953) – Pranav Hosangadi Jan 27 '21 at 15:00

1 Answers1

2

You can do it using timedelta :

from datetime import datetime, timedelta
yesterday = datetime.today() - timedelta(days=1)

Output will be :

datetime.datetime(2021, 1, 26, 20, 27, 25, 849797)
Girish
  • 366
  • 3
  • 15