Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can we do date and time math in Python?
It is very easy to do date and time math 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.
Syntax
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 integers, longs, or floats, and may be positive or negative.
Adding and Subtracting Time
An example of using the timedelta objects to subtract time from the current datetime ?
import datetime
old_time = datetime.datetime.now()
print("Current time:", old_time)
new_time = old_time - datetime.timedelta(hours=2, minutes=10)
print("Time 2 hours 10 minutes ago:", new_time)
Current time: 2024-01-04 11:09:00.694602 Time 2 hours 10 minutes ago: 2024-01-04 08:59:00.694602
Adding Time to Current Date
You can also add time using positive values in timedelta ?
import datetime
current_time = datetime.datetime.now()
print("Current time:", current_time)
future_time = current_time + datetime.timedelta(days=7, hours=3)
print("7 days and 3 hours later:", future_time)
Current time: 2024-01-04 11:09:00.694602 7 days and 3 hours later: 2024-01-11 14:09:00.694602
Calculating Difference Between Dates
Subtracting two datetime objects gives a timedelta object. This timedelta object can be used to find the exact difference between the two datetimes ?
import datetime
import time
t1 = datetime.datetime.now()
time.sleep(2) # Wait 2 seconds
t2 = datetime.datetime.now()
difference = t2 - t1
print("Time difference:", difference)
print("Type of difference:", type(difference))
print("Difference in seconds:", difference.total_seconds())
Time difference: 0:00:02.003456 Type of difference: <class 'datetime.timedelta'> Difference in seconds: 2.003456
Working with Time Objects
timedelta() arithmetic is not supported for datetime.time() objects. If you need to use offsets from an existing datetime.time() object, use datetime.datetime.combine() to form a datetime.datetime() instance, do your calculations, and extract the time again with the .time() method ?
import datetime
# Create a time object
time_obj = datetime.time(14, 30, 0) # 2:30 PM
today = datetime.date.today()
# Combine with today's date
datetime_obj = datetime.datetime.combine(today, time_obj)
print("Original datetime:", datetime_obj)
# Add 2 hours
new_datetime = datetime_obj + datetime.timedelta(hours=2)
print("After adding 2 hours:", new_datetime)
# Extract just the time
new_time = new_datetime.time()
print("New time only:", new_time)
Original datetime: 2024-01-04 14:30:00 After adding 2 hours: 2024-01-04 16:30:00 New time only: 16:30:00
Conclusion
Python's datetime.timedelta makes date and time arithmetic simple and intuitive. Use it to add or subtract time periods from datetime objects, and remember to convert time objects to datetime objects before performing arithmetic operations.
