How to Subtract Minutes from a Date in Python?

Problem Formulation and Solution Overview

This article will show you how to subtract minutes from a datetime in Python.

To make it more interesting, we have the following running scenario:

ToyMax has 200 employees. All employees must swipe in and out daily using a time card reader. Sometimes the employee swipe-in times do not appear to be correct. They seem to be off by five (5) minutes.

For the examples in this article, the current datetime for swipe-in times is used.


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

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


Method 1: Use timedelta()

This example uses timedelta() from the datetime library to subtract five (5) minutes from a specified datetime. In this case, the current datetime.

import datetime
from datetime import timedelta   

swipe_in  = datetime.datetime.today()
new_swipe_in = (swipe_in - timedelta(minutes=5))
print(new_swipe_in)

The first line in the above code imports the datetime library

The following line calls the timedelta() function from this library. This function allows us to define durations to modify, such as days, minutes, hours, etc., and perform operations thereon.

The next line retrieves and saves the current datetime to swipe_in. For this example, the contents display below.

2022-10-03 07:05:57.520864

The following line performs the subtraction operation by calling timedelta() and passing it one (1) argument, a duration (minutes=5). This number of minutes is subtracted from swipe_in, saved to new_wipe_in and output to the terminal.

2022-10-03 07:00:57.520864

Comparing the two outputs, notice that new_swipe_in is five (5) minutes less than swipe_in.


Method 2: Use shift() from the arrow library

This example uses the shift() function from the arrow library to subtract five (5) minutes from a specified datetime. In this case, the current datetime.

To run this code error-free, the arrow library needs to be installed. Click here for instructions.

import arrow

swipe_in  = arrow.utcnow()
new_swipe_in = swipe_in.shift(minutes=-5)
print(new_swipe_in)

This first line imports the arrow library.

This provides us access to the utcnow() function to retrieve the current datetime, and shift(). This function allows us to define durations to modify, such as days, minutes, hours, etc., and perform operations thereon.

The next line retrieves and saves the current datetime to swipe_in. For this example, the contents display below.

2022-10-03 07:05:57.520864

The following line performs the subtraction operation by applying shift(), and passing one (1) argument (minutes =-5). The result saves to new_swipe_in and output to the terminal.

2022-10-03 07:00:57.520864

Comparing the two outputs, notice that new_swipe_in is five (5) minutes less than swipe_in.


Method 3: Use relativedelta()

This example imports the datetime library to retrieve the current date and the dateutil library to subtract five (5) minutes from a specified datetime. In this case, the current datetime.

To run this code error-free, the dateutil library needs to be installed. Click here for instructions.

from datetime import datetime
from dateutil.relativedelta import relativedelta

swipe_in  = datetime.now()
new_swipe_in = swipe_in - relativedelta(minutes=5)
print(new_swipe_in)

The first line imports the datetime library is imported which gives us access to the now() function. This function retrieves the current datetime.

The next line retrieves and saves the current datetime to swipe_in. For this example, the contents display below.

2022-10-03 07:05:57.520864

The following line performs the subtraction operation by calling relativedelta() and passing it one (1) argument, a duration (minutes=5). This is subtracted from swipe_in, saved to new_wipe_in and output to the terminal.

2022-10-03 07:00:57.520864

Comparing the two outputs, notice that new_swipe_in is five (5) minutes less than swipe_in.


Method 4: pandas and timedelta()

This example imports the pandas library and the timedelta() function to subtract five (5) minutes from a specified DataFrame column.

To run this code error-free, the pandas library needs to be installed. Click here for instructions.

To follow along, save the data below as times.csv and place this in the current working directory.

IDSwipeInSwipeOut
1982022-10-03 07:05:57.1397882022-10-03 17:00:57.120864
1992022-10-03 07:05:57.2208642022-10-03 17:00:57.220864
2002022-10-03 07:05:56.4808642022-10-03 17:00:57.320864
2012022-10-03 07:05:56.4770642022-10-03 17:00:57.420864
2022022-10-03 07:05:56.4108642022-10-03 17:00:57.620864
import pandas as pd
from datetime import timedelta

df  = pd.read_csv('times.csv')
df['SwipeIn'] = pd.to_datetime(df['SwipeIn']) - timedelta(minutes=5)
df.to_csv('times1.csv')

The first line imports the pandas library. This allows us to work with CSV files and DataFrames, just to name a few!

The following line calls the timedelta() function from the datetime library. This function allows us to define durations to modify, such as days, minutes, hours, etc., and perform operations thereon.

Next, we read the times.csv file created above and save this to a DataFrame df.

The following line does all the work! Here we collectively subtract five (5) minutes from each DataFrame Column, SwipeIn time. These results are then saved to a new CSV file, times1.csv file. The contents of this file are displayed below.

IDSwipeInSwipeOut
1982022-10-03 07:00:57.1397882022-10-03 17:00:57.120864
1992022-10-03 07:00:57.2208642022-10-03 17:00:57.220864
2002022-10-03 07:00:56.4808642022-10-03 17:00:57.320864
2012022-10-03 07:00:56.4770642022-10-03 17:00:57.420864
2022022-10-03 07:00:56.4108642022-10-03 17:00:57.620864

Summary

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

Good Luck & Happy Coding!


Programming Humor – Python

“I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I’m leaving you.”xkcd