- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find time difference using Python?
It is very easy to do date and time maths in Python using time delta objects. Whenever you want to add or subtract to a date/time, use a DateTime.datetime(), then add or subtract date time.time delta() instances. A time delta object represents a duration, the difference between two dates or times. The time delta constructor has the following function signature
DateTime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])¶
Note: All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. You can read more about it here https://docs.python.org/2/library/datetime.html#timedelta-objects
An example of using the time delta objects and dates
import datetime old_time = datetime.datetime.now() print(old_time) new_time = old_time - datetime.timedelta(hours=2, minutes=10) print(new_time)
This will give the output
2018-01-04 11:09:00.694602 2018-01-04 08:59:00.694602
time delta() arithmetic is not supported for date time.time() objects; if you need to use offsets from an existing date time.time() object, just use date time.datetime.combine() to form a date time.date time() instance, do your calculations, and 'extract' the time again with the .time() method.
Subtracting 2 date time objects gives a time delta object. This time delta object can be used to find the exact difference between the 2 date times.
t1 = datetime.datetime.now() t2 = datetime.datetime.now() print(t1 - t2) print(type(t1 - t2))
This will give the output
-1 day, 23:59:56.653627 <class 'datetime.timedelta'>
- Python program to find difference between current time and given time
- How to access and convert time using the time library in Python
- How to print current date and time using Python?
- How to check file last access time using Python?
- How to Find LCM using Python?
- How to find PHP execution time?
- Program to find average waiting time in Python
- How to find difference between 2 files in Python?
- MySQL query to check how to get time difference
- How to find keith numbers using Python?
- How to find a file using Python?
- How to compare time in different time zones in Python?
- Program to find nearest time by reusing same digits of given time in python
- How to Find Hash of File using Python?
- How to Find HCF or GCD using Python?