Python Subtract Seconds from DateTime Example

By Hardik Savani October 30, 2023 Category : Python

If you need to see example of python subtract seconds to datetime example. it's simple example of how to subtract seconds to date in python. I would like to show you how to subtract second to current date in python. I explained simply step by step python minus seconds to date in dataframe. Here, Creating a basic example of python subtract 1 second to date string.

In this example, I will give two examples for you of how to subtract seconds to date in python and how to subtract seconds to today's datetime in python. therefore, let's see below example code and try it.

You can use these examples with python3 (Python 3) version.

Example 1: Python Subtract Seconds to DateTime

main.py

from datetime import datetime
from dateutil.relativedelta import relativedelta
  
myDateString = "2022-06-01"
  
myDate = datetime.strptime(myDateString, "%Y-%m-%d")
  
subSecondsNumber = 50;
newDate = myDate - relativedelta(seconds=subSecondsNumber)
  
print("Old Date :")
print(myDate)
  
print("New Date :")
print(newDate)

Output:

Old Date :
2022-06-01 00:00:00
New Date :
2022-05-31 23:59:10

Example 2: Python Subtract Seconds to Current DateTime

main.py

from datetime import datetime
from dateutil.relativedelta import relativedelta
  
myDate = datetime.today()
  
subSecondsNumber = 50;
newDate = myDate - relativedelta(seconds=subSecondsNumber)
  
print("Old Date :")
print(myDate)
  
print("New Date :")
print(newDate)

Output:

	
Old Date :
2022-06-22 09:36:35.302041
New Date :
2022-06-22 09:35:45.302041

I hope it can help you...

Tags :
Shares