We often need to subtract two datetime in python. In this tutorial, we will introduce you how to do.
Method 1: subtract two datetime directly
We can subtract two datetime directly in python. For example:
import datetime date_1 = datetime.datetime(year = 2022, month=2, day=2, hour=14, minute=2, second=13) date_2 = datetime.datetime(year = 2022, month=2, day=2, hour=16, minute=3, second=13) date_3 = date_2 - date_1 print(date_3) print(date_3.seconds)
Here we use date_2-date_1 to get date_3 directly.
Run this code, we will get:
2:01:00 7260
Here we should notice date_1 and date_2 are datetime object. If your datetime is string, you should convert it to datetime type.
Method 2: convert datetime to timestamp for subtract
For example:
sec = datetime.datetime.timestamp(date_2) - datetime.datetime.timestamp(date_1) print(sec)
We can use datetime.datetime.timestamp() to convert a datetime object to timestamp.
Then we will see:
7260.0