Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.
Syntax : datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Returns : Date
Code #1:
Python3
from datetime import datetime, timedelta
ini_time_for_now = datetime.now()
print ("initial_date", str(ini_time_for_now))
future_date_after_2yrs = ini_time_for_now + \
timedelta(days = 730)
future_date_after_2days = ini_time_for_now + \
timedelta(days = 2)
print('future_date_after_2yrs:', str(future_date_after_2yrs))
print('future_date_after_2days:', str(future_date_after_2days))
|
Output:initial_date 2019-02-27 12:41:45.018389
future_date_after_2yrs: 2021-02-26 12:41:45.018389
future_date_after_2days: 2019-03-01 12:41:45.018389
Code #2:
Python3
from datetime import datetime, timedelta
ini_time_for_now = datetime.now()
print ('initial_date:', str(ini_time_for_now))
past_date_before_2yrs = ini_time_for_now - \
timedelta(days = 730)
past_date_before_2hours = ini_time_for_now - \
timedelta(hours = 2)
print('past_date_before_2yrs:', str(past_date_before_2yrs))
print('past_date_before_2hours:', str(past_date_before_2hours))
|
Output:initial_date 2019-02-27 12:41:46.104662
past_date_before_2yrs: 2017-02-27 12:41:46.104662
past_date_after_2days: 2019-02-27 10:41:46.104662
Code #3:
Python3
from datetime import datetime, timedelta
ini_time_for_now = datetime.now()
print ("initial_date", str(ini_time_for_now))
new_final_time = ini_time_for_now + \
timedelta(days = 2)
print ("new_final_time", str(new_final_time))
print('Time difference:', str(new_final_time - \
ini_time_for_now))
|
Output:initial_date 2019-02-27 12:41:47.386595
new_final_time 2019-03-01 12:41:47.386595
Time difference: 2 days, 0:00:00
Subtracting a timedelta object from a date or datetime object:
Approach:
Create a timedelta object with the desired time difference.
Subtract the timedelta object from a date or datetime object using the – operator.
Python3
import datetime
today = datetime.date.today()
three_days_ago = today - datetime.timedelta(days=3)
print("Today:", today)
print("Three days ago:", three_days_ago)
|
OutputToday: 2023-03-24
Three days ago: 2023-03-21
Time complexity: O(1)
Auxiliary Space: O(1)
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Last Updated :
24 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...