Prerequisite: datetime module
In Python, date and time are not a data type of its own, but a module named datetime can be imported to work with the date as well as time. Datetime module comes built into Python, so there is no need to install it externally.
To work with date, datetime module provides the date class and timedelta class is used to calculate differences in date. Let’s have a look at them.
- Date class: When an object of this class is instantiated, it represents a date in the format YYYY-MM-DD. To return the current local date today() function of date class is used. today() function comes with several attributes (year, month and day). These can be printed individually.
Syntax:
date.today()
- Timedelta class: Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.
Syntax:
datetime.timedelta(days=0, seconds=0, microseconds=0,
milliseconds=0, minutes=0, hours=0, weeks=0)
Returns: Date
Below is the implementation
Python3
from datetime import date
from datetime import timedelta
today = date.today()
print ( "Today is: " , today)
yesterday = today - timedelta(days = 1 )
print ( "Yesterday was: " , yesterday)
|
Output:
Today is: 2019-12-11
Yesterday was: 2019-12-10
You just have to subtract no. of days using ‘timedelta’ that you want to get back in order to get the date from the past.
For example, on subtracting two we will get the date of the day before yesterday.
Python3
from datetime import date
from datetime import timedelta
today = date.today()
print ( "Today is: " , today)
yesterday = today - timedelta(days = 2 )
print ( "Day before yesterday was: " , yesterday)
|
Output:
Today is: 2019-12-11
Day before yesterday was: 2019-12-09
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
02 Sep, 2021
Like Article
Save Article