- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find yesterday’s, today’s and tomorrow’s date in Python
When it is required to find yesterday, today and tomorrow’s date with respect to current date, the current time is determined, and a method is used (in built) that helps find previous day and next day’s dates.
Below is a demonstration of the same −
Example
from datetime import datetime, timedelta present = datetime.now() yesterday = present - timedelta(1) tomorrow = present + timedelta(1) print("Yesterday was :") print(yesterday.strftime('%d-%m-%Y')) print("Today is :") print(present.strftime('%d-%m-%Y')) print("Tomorrow would be :") print(tomorrow.strftime('%d-%m-%Y'))
Output
Yesterday was : 05-04-2021 Today is : 06-04-2021 Tomorrow would be : 07-04-2021
Explanation
The required packages are imported into the environment.
The current date is determined using the ‘now’ method present in ‘datetime’ package.
It is assigned to a variable.
The ‘timedelta’ method is used to find the previous or next days, by passing the number as parameter.
When the next day has to be found, the function is added.
When the previous day has to be found, the function is subtracted.
The output is displayed on the console.
Advertisements