How to Subtract Days from a Date

5/5 - (4 votes)

Problem Formulation and Solution Overview

In this article, you’ll learn various ways to subtract days from a date in Python.

This article is based on Rivers Clothing and has examples on how to set and subtract a date x number of days, AND, how to subtract one date from another date.

πŸ’¬ Question: How would we write Python code to subtract days from a date?

We can accomplish this task by one of the following options:


Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

  • The arrow library easily retrieves dates and times.
  • The Pandas library enables access to/from a DataFrame.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.


$ pip install arrow

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

If the installation was successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required libraries.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import datetime
from datetime import date
import arrow
import pandas as pd 

Method 1: Use datetime.timedelta()

This method retrieves the current date as a string and splits it into a List. Then, the current date (std_payday) is configured, and ten (10) days are subtracted (datetime.timedelta(10)) from same to return a new date.

get_today  = str(date.today()).split('-')
std_payday = datetime.date(int(get_today[0]), int(get_today[1]), 25)
chg_days   = datetime.timedelta(10)
new_payday = std_payday - chg_days
print(new_payday)

This code does the following:

  • Declares get_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 std_pay 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 chg_days which uses timedelta and passes an integer, (10) which is the number of days to subtract from the original day (25).
  • Declares new_payday and subtracts std_payday from chg_days.

Finally, the contents of new_payday is sent to the terminal.

Output

Rivers Clothing’s payroll for the current month is set to the following date.

2022-05-15

Method 2: Use arrow and shift()

This method uses the arrow library, to retrieve the current date (arrow.utcnow()). Then shift() is applied to the same to subtract days from the current date, resulting in a new date.

get_today  = arrow.utcnow()
new_payday = get_today.shift(days=-3)
print(str(new_payday)[:10])

This code does the following:

  • Declares get_today which retrieves the current date (yyyy-mm-dd), and returns a date object.
  • Declares new_payday which applies shift() to get_today and passes the number of days to subtract (get_today.shift(days=-3)).

Finally, the output is sent to the terminal.

The Ultimate Guide to Slicing in Python

Output 1

If new_payday was output to the terminal without converting it to a string and applying slicing, the following would be the output.

2022-05-27T12:17:49.836432+00:00

Output 2

If new_payday was converted to a string data type and slicing applied, the following would be the output.

2022-05-24

Method 3: Use Pandas DateOffset()

In this method, datetime.striptime() is called and creates a date object. This date object is modified by indicating the number of days to subtract (pd.DateOffset(days=3)) from the original date to return the new date.

from datetime import datetime

cur_date   = '2022-05-27'
date_obj   = datetime.strptime(cur_date, '%Y-%m-%d')
new_payday = date_obj - pd.DateOffset(days=3)
print(str(new_payday)[:10])

πŸ’‘Note: In addition to the required libraries mentioned in the Preparation section, this method needs an additional item from the datetime library imported as follows: from datetime import datetime

This code then does the following:

  • Declares cur_date and assigns it a Date string.
  • Next, cur_date calls datetime.striptime() which takes two (2) arguments: a date string and returns a Date Object.
  • Then, three (3) days are subtracted from cur_date and saved to new_payday.

Finally, the output is sent to the terminal.

Output 1

If new_payday was output to the terminal without converting it to a string and applying slicing, the following would be the output.

2022-05-27 00:00:00

Output 2

If new_payday was converted to a string data type and slicing applied, the following would be the output.

2022-05-27

Method 4: Use Pandas to subtract date columns

What if you don’t want to set a new date but want to find the difference between one date and another? This example creates a DataFrame, subtracts one date from another, and outputs the difference in days.

df = pd.DataFrame(columns=['hired', 'fired'])

df.hired = ['2020-01-24', '2022-01-27']
df.fired = ['2021-01-13', '2022-04-29']

df.hired = pd.to_datetime(df.hired)
df.fired = pd.to_datetime(df.fired)

diff     = (df.fired - df.hired)
print(diff)

This code does the following:

  • First, a DataFrame is created containing two (2) columns: hired and fired. The result saves to df.
  • The following two (2) lines add two (2) rows to the DataFrame df and save to the appropriate variable (df.hired or df.fired).
  • Then these two (2) lines are converted to a Datetime object and saved to the appropriate variable mentioned above.
  • The two (2) dates are subtracted and saved to diff.

Finally, the output is sent to the terminal.

10 Minutes to Pandas in 5 Minutes (Okay 8)

Output

0355 days
192 days
dtype: timedelta64[ns]

Bonus: Read CSV and subtract date columns

What if you don’t want to set a new date but want to find the difference between one date and another? This example reads in a small CSV file, subtracts one date from another, and outputs the difference in days.

df = pd.read_csv('dates.csv', usecols=['hired', 'fired'], header=0)

df['hired'] = pd.to_datetime(df['hired'], errors='coerce')
df['fired'] = pd.to_datetime(df['fired'], errors='coerce')
df['diff'] = df['fired'] - df['hired']
print(df)

This code does the following:

  • Reads in a small CSV file containing two (2) rows. Each row has a hired date and a fired date and saves to df.
  • The following two (2) lines convert the DataFrame columns hired and fired to a Date object and saves to the same.
  • Next, a new column diff is added and contains the number of days between the fired and hired date.

Finally, the output is sent to the terminal.

hiredfireddiff
02021-10-262022-12-25425 days
12021-11-112022-03-31140 days

Summary

These five (5) methods of subtracting dates should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!