Python Subtract Hours from Datetime Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Subtract Year to Date in Python?
- How to Add Years to Date in Python?
- How to Subtract Months to Date in Python?
- How to Add Months to Date in Python?
- How to Subtract Days from Date in Python?
- How to Add Days to Date in Python?
- How to Get Current Second in Python?
- How to Get Current Minute in Python?
- How to Get Current Hour in Python?
- How to Get Current Time in Python?
- How to Get Current Date and Time in Python?