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 I apply an offset on the current time in Python?
Whenever you want to add or subtract (apply an offset) 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 ints, longs, or floats, and may be positive or negative.
Adding Time Offset
Here's how to add time to the current datetime ?
import datetime
current_time = datetime.datetime.now()
print("Current time:", current_time)
# Add 2 hours and 30 minutes
future_time = current_time + datetime.timedelta(hours=2, minutes=30)
print("Future time:", future_time)
Current time: 2024-01-04 11:09:00.694602 Future time: 2024-01-04 13:39:00.694602
Subtracting Time Offset
You can also subtract time to get a past datetime ?
import datetime
current_time = datetime.datetime.now()
print("Current time:", current_time)
# Subtract 2 hours and 10 minutes
past_time = current_time - datetime.timedelta(hours=2, minutes=10)
print("Past time:", past_time)
Current time: 2024-01-04 11:09:00.694602 Past time: 2024-01-04 08:59:00.694602
Multiple Time Units
You can combine multiple time units in a single timedelta ?
import datetime
current_time = datetime.datetime.now()
print("Current time:", current_time)
# Add 1 week, 3 days, 4 hours, and 30 minutes
offset_time = current_time + datetime.timedelta(weeks=1, days=3, hours=4, minutes=30)
print("Offset time:", offset_time)
Current time: 2024-01-04 11:09:00.694602 Offset time: 2024-01-15 15:39:00.694602
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
print("Original time:", time_obj)
# Combine with today's date
today = datetime.date.today()
dt = datetime.datetime.combine(today, time_obj)
# Add 2 hours
new_dt = dt + datetime.timedelta(hours=2)
# Extract the time
new_time = new_dt.time()
print("New time:", new_time)
Original time: 14:30:00 New time: 16:30:00
Conclusion
Use datetime.timedelta() to apply time offsets to datetime objects. For time objects, combine with a date first, apply the offset, then extract the time component back.
