Problem Formulation and Solution Overview
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.
Preparation
- 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.
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 callsdatetime.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 usestimedelta
and passes an integer, (10)
which is the number of days to subtract from the original day (25)
. - Declares
new_payday
and subtractsstd_payday
fromchg_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 appliesshift()
toget_today
and passes the number of days to subtract (get_today.shift(days=-3)
).
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-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
callsdatetime.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 tonew_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
was converted to a string data type and slicing applied, the following would be the output.new_payday
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
andfired
. The result saves todf
. - The following two (2) lines add two (2) rows to the DataFrame
df
and save to the appropriate variable (df.hired
ordf.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.
Output
0 | 355 days |
1 | 92 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
andfired
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
andhired
date.
Finally, the output is sent to the terminal.
hired | fired | diff | |
0 | 2021-10-26 | 2022-12-25 | 425 days |
1 | 2021-11-11 | 2022-03-31 | 140 days |
Summary

At university, I found my love of writing and coding. Both of which I was able to use in my career.
During the past 15 years, I have held a number of positions such as:
In-house Corporate Technical Writer for various software programs such as Navision and Microsoft CRM
Corporate Trainer (staff of 30+)
Programming Instructor
Implementation Specialist for Navision and Microsoft CRM
Senior PHP Coder