Subtracting dates in Python is a common task that you might come across when dealing with data that contains timestamps.
Whether you need to know the number of days between two dates for analysis, or simply calculate the age of a person, Python makes it simple with the use of its built-in datetime module.
This tutorial will guide you through the process of subtracting dates in Python.
Step 1: Importing the datetime module
First, you need to import the datetime module. This module supplies classes to manipulate dates and times. Here is how to do it:
1 |
import datetime |
Step 2: Defining the Dates
Next, you need to define the dates you want to subtract. Dates in the datetime module are not strings but datetime objects, hence you should create them in a certain way:
1 2 |
date1 = datetime.date(2021, 7, 1) date2 = datetime.date(2022, 7, 1) |
In this case, the dates are July 1st, 2021, and July 1st, 2022 respectively.
Step 3: Subtracting the Dates
The subtraction of the dates is as simple as subtracting two numbers. Here is how you can do it:
1 |
diff = date2 - date1 |
This will return a datetime.timedelta object which represents the difference between two dates or times.
Step 4: Getting the Number of Days
If you are interested in the number of days between the two dates, you can get it by calling the days attribute of the timedelta object:
1 |
days = diff.days |
Here is what you will get:
365
Step 5: Printing the Result
Finally, you can print the result:
1 |
print(f'There are {days} days between {date1} and {date2}') |
This will print:
There are 365 days between 2021-07-01 and 2022-07-01
Full code
1 2 3 4 5 6 7 8 9 |
import datetime date1 = datetime.date(2021, 7, 1) date2 = datetime.date(2022, 7, 1) diff = date2 - date1 days = diff.days print(f'There are {days} days between {date1} and {date2}') |
There are 365 days between 2021-07-01 and 2022-07-01
Conclusion
As shown, subtracting dates in Python is a straightforward process. By utilizing the built-in datetime module, one can efficiently perform date operations for various purposes.
Keep in mind that Python’s ability to manipulate dates and times extends far beyond what has been introduced in this tutorial. Feel free to explore the datetime documentation for more information.