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.
- Timdelta 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.
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) Returns: Date
Below is the implementation
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.
Today is: 2019-12-11 Day before yesterday was: 2019-12-09
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- How to print date starting from the given date for n number of days using Pandas?
- Get current date using Python
- Get Current Date and Time using Python
- Get Month from date in Pandas - Python
- Get month and Year from Date in Pandas - Python
- Get Day from date in Pandas - Python
- Get the day from a date in Pandas
- Python | Working with date and time using Pandas
- Python | Swap Name and Date using Group Capturing in Regex
- Display date and time in videos using OpenCV - Python
- How to sort date in excel using Pandas?
- Extract date from a specified column of a given Pandas DataFrame using Regex
- How to extract date from Excel file using Pandas?
- Time Functions in Python | Set-2 (Date Manipulations)
- Python | Pandas Timestamp.date
- Python | Pandas DatetimeIndex.date
- Python program to find day of the week for a given date
- Python | Pandas Series.dt.date
- Python | Sort given list of dictionaries by date
- Python | Create an empty text file with current date as its name
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.