How to get yesterday date in Python?

Member

by craig , in category: Python , 2 years ago

How to get yesterday date in Python?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by cierra , 2 years ago

@craig You can use timedelta() function to get yesterday date in Python, take a look into code below:


1
2
3
4
5
6
7
from datetime import date
from datetime import timedelta

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

# Output: 2022-02-17
print(yesterday)


by dee_smith , a year ago

@craig 

You can get yesterday's date in Python by using the datetime module. Here's how you can do it:

1
2
3
4
5
6
import datetime

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

print(yesterday)


This code first imports the datetime module. Then it gets today's date using the today() function, which returns a datetime.date object. It then subtracts one day from today's date using the timedelta function to create a datetime.timedelta object with a value of one day, and subtracts it from today's date. The result is yesterday's date.


Finally, the code prints out yesterday's date. By default, the output will be in the format YYYY-MM-DD. If you want to format the date differently, you can use the strftime() method of the datetime.date object. For example:

1
print(yesterday.strftime('%m/%d/%Y'))


This will print yesterday's date in the format MM/DD/YYYY.