ItSolutionStuff.com

Python Subtract Hours from Datetime Example

By Hardik Savani β€’ October 30, 2023
Python

This is a short guide on python subtract hours to time example. if you have question about how to subtract hours to datetime in python then I will give simple example with solution. Here you will learn how to subtract hour to current date in python. it's simple example of python minus hours to time in dataframe. Alright, letÒ€ℒs dive into the steps.

In this example, I will give two examples for you of how to subtract hours to datetime in python and how to subtract hours to today's time 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 Hours to DateTime

main.py

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

Output:

Old Date :
2022-06-01 00:00:00
New Date :
2022-05-31 22:00:00

Example 2: Python Subtract Hours to Current DateTime

main.py

from datetime import datetime
from dateutil.relativedelta import relativedelta
  
myDate = datetime.today()
    
subHoursNumber = 2;
newDate = myDate - relativedelta(hours=subHoursNumber)
 
print("Old Date :")
print(myDate)
  
print("New Date :")
print(newDate)

Output:

Old Date :
2022-06-17 09:20:00.447360
New Date :
2022-06-17 07:20:00.447360

I hope it can help you...

Tags: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

πŸ“Ί Subscribe on YouTube

We Are Recommending You

β˜…

How to Subtract Year to Date in Python?

Read Now β†’
β˜…

How to Add Years to Date in Python?

Read Now β†’
β˜…

How to Subtract Months to Date in Python?

Read Now β†’
β˜…

How to Add Months to Date in Python?

Read Now β†’
β˜…

How to Subtract Days from Date in Python?

Read Now β†’
β˜…

How to Add Days to Date in Python?

Read Now β†’
β˜…

How to Get Current Second in Python?

Read Now β†’
β˜…

How to Get Current Minute in Python?

Read Now β†’
β˜…

How to Get Current Hour in Python?

Read Now β†’
β˜…

How to Get Current Time in Python?

Read Now β†’
β˜…

How to Get Current Date and Time in Python?

Read Now β†’