- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 can we do date and time math in Python?
It is very easy to do date and time maths in Python using timedelta objects. Whenever you want to add or subtract to a date/time, use a datetime.datetime(), then add or subtract datetime.timedelta() instances. A timedelta object represents a duration, the difference between two dates or times. The timedelta 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
Example
An example of using the timedelta 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)
Output
This will give the output −
2018-01-04 11:09:00.694602 2018-01-04 08:59:00.694602
timedelta() arithmetic is not supported for datetime.time() objects; if you need to use offsets from an existing datetime.time() object, just use datetime.datetime.combine() to form a datetime.datetime() instance, do your calculations, and 'extract' the time again with the .time() method.
Subtracting 2 datetime objects gives a timedelta object. This timedelta object can be used to find the exact difference between the 2 datetimes.
Example
t1 = datetime.datetime.now() t2 = datetime.datetime.now() print(t1 - t2) print(type(t1 - t2))
Output
This will give the output −
-1 day, 23:59:56.653627 <class 'datetime.timedelta'>
- Related Articles
- Can we do math operation on Python Strings?
- How can we offload the time/date handling in MySQL?
- How To Do Math With Lists in python ?
- How to do Python math at command line?
- How can we insert current date and time automatically on inserting values in other columns in MySQL?
- How do we measure time?
- How do I get the current date and time in JavaScript?
- How do you format date and time in Android using Kotlin?
- How to get current date and time in Python?
- How to get formatted date and time in Python?
- How can I get time and date since epoch in JavaScript?
- How can I get the current time and date in Kotlin?
- Python Basic date and time types
- How to print current date and time using Python?
- How do we use Python regular expression to match a date string?
