- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
How can I subtract a day from a Python date?
It is essential to have a module that can modify date and time since, as we all know, they are utilized in applications where we must keep track of date and time. A DateTime module in Python deals with dates and times. Python comes with a built-in datetime module.
Installation of two new libraries is necessary before any data modification may take place.
- Dates and timings are quickly retrieved using the arrow library.
- A DataFrame may be accessed and used thanks to the Pandas library.
Go to an IDE console to install these libraries. Run the code below at the ($) command prompt. The command prompt for the terminal used in this illustration is denoted by a dollar symbol ($). The prompt on your terminal can be different.
time − It shows time, independent of any particular day with attributes are hour, minute, second, microsecond, and tzinfo.
timedelta − It is used to manipulate Date.
date − It shows the date according to the Georgian calendar with attributes are year, month and day.
tzinfo − It provides information about the Time zone.
datetime − It is a collection of Dates and Times with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo.
class datetime.timedelta(days=10, month ,hour, minute, second, microsecond, tzinfo) Returns: Date
Note − if we doesn’t specify by default it takes integer as an day.
Initialise a string and use today method to retrieve the current date and split method to split it into a List.
Declare a new variable which calls datetime.date() and takes three arguments: current year, current month and day.
Declare a variable which uses timedelta and passes an integer which is the number of days to subtract from the original day.
Return the difference of the datetime.date() variable and timedelta variable.
Method 1: Use datetime.timedelta()
This method retrieves the current date as a string and splits it into a List. Then, the current date (payday) is configured, and ten (10) days are subtracted (datetime.timedelta(10)) from same to return a new date.
#importing necessary functions import datetime from datetime import date import pandas as pd #storing the value of date.today in a variable today today = str(date.today()).split('-') #Declares payday which calls datetime.date() and takes three (3) integer arguments: current year (int(get_today)), current month (int(get_today)) payday= datetime.date(int(today), int(today), 25) #Declares chqday which uses timedelta and passes an integer, (10) chqday = datetime.timedelta(10) #Declares n_payday which subtracts payday from chqday n_payday= payday - chqday #printing the payday print("Payday =",payday)
Payday = 2022-11-25
Declares today which retrieves the current date (yyyy-mm-dd), and splits the date string on the hyphen (split('-')). This returns the current date as a List of Strings ['2022', '05', '27']. Declares payday which calls datetime.date() and takes three (3) integer arguments: current year (int(get_today)), current month (int(get_today)), and day, (25). Declares chqday which uses timedelta and passes an integer, (10) which is the number of days to subtract from the original day (25). Declares n_payday which subtracts payday from chqday. Finally, the output of n_paydy is sent to the terminal.
Method 2: Use Pandas to subtract date columns
What if you want to determine the difference between two dates but don't want to establish a new one? In this example, two dates are subtracted from one another, and the result is output as the difference in days.
#importing important functions import datetime from datetime import date import pandas as pd #outcome of dataframe is stored in df df = pd.DataFrame(columns=['hired', 'fired']) #two rows to the DataFrame df and save the data to the relevant variable (df.hired or df.fired) df.hired = ['2022-09-07', '2022-10-29'] df.fired = ['2021-09-07', '2022-04-29'] #Datetime object is created from these two lines and stored to the relevant variable stated above df.hired = pd.to_datetime(df.hired) df.fired = pd.to_datetime(df.fired) #storing the difference of df.fired and df.hired in diff. diff = (df.fired - df.hired) #printing the diff print(diff)
0 -365 days 1 -183 days dtype: timedelta64[ns]
First, a DataFrame with the columns recruited and dismissed is generated. The outcome is saved to df. The next two lines add two rows to the DataFrame df and save the data to the relevant variable (df.hired or df.fired). Then a Datetime object is created from these two lines and stored to the relevant variable stated above. It subtracts the two dates and saves the result to diff.
datetime is a collection of Dates and Times with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo. timedelta() is used to manipulate date. Calculate the difference between timedelta and datetime.date variable to return the desired output i.e to subtract a day from Python date.
- Related Articles
- How can I subtract tuple of tuples from a tuple in Python?
- How to subtract Python timedelta from date in Python?
- How can we fetch month and day from a given date in MySQL?
- How can I select date from a datepicker div using Selenium Webdriver?
- How to subtract number of days from a date to get the previous date in R?
- Get the day from a date in Pandas
- How to subtract seconds from all the date records in a MySQL column?
- How to Add or Subtract Hours from a Date/Time Field in Excel?
- How can I source a Python file from another Python file?
- How to get a Date from year, month and day in Java?
- Is there a way to subtract number of days from a date in MySQL?