How can I subtract a day from a Python date?


Introduction

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 Date/Time Tutorial). 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.

Methods used

  • 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.

Syntax

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.

Algorithm

  • 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()

Example

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[0])), current month (int(get_today[1])) payday= datetime.date(int(today[0]), int(today[1]), 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)

Output

Payday = 2022-11-25

Code Explanation

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[0])), current month (int(get_today[1])), 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

Example

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)

Output

0   -365 days
1   -183 days
dtype: timedelta64[ns]

Code Explanation

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.

Conclusion

The 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.

Updated on: 27-Aug-2023

23K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements