To add minutes to a datetime using Python, the easiest way is to use the Python timedelta() function from the datetime module.
from datetime import timedelta, datetime
now = datetime.now()
one_minute_in_future = now + timedelta(minutes=1)
sixty_minutes_in_future = now + timedelta(minutes=60)
one_day_in_future = now + timedelta(minutes=1440)
print(now)
print(one_minute_in_future)
print(sixty_minutes_in_future)
print(one_day_in_future)
#Output:
2022-05-05 15:45:53.655282
2022-05-05 15:46:53.655282
2022-05-05 16:45:53.655282
2022-05-06 15:45:53.655282
When working with data in Python, many times we are working with datetimes. Being able to manipulate and change dates easily is very important for efficient processing.
One such change is to be able to add minutes to a datetime variable.
With Python, we can easily add minutes to a date with the help of the datetime module.
To add minutes to a date in Python, we can use the timedelta() function from the datetime module.
Below is code that shows you how to add days to get some datetimes in the future using Python.
from datetime import timedelta, datetime
now = datetime.now()
one_minute_in_future = now + timedelta(minutes=1)
sixty_minutes_in_future = now + timedelta(minutes=60)
one_day_in_future = now + timedelta(minutes=1440)
print(now)
print(one_minute_in_future)
print(sixty_minutes_in_future)
print(one_day_in_future)
#Output:
2022-05-05 15:45:53.655282
2022-05-05 15:46:53.655282
2022-05-05 16:45:53.655282
2022-05-06 15:45:53.655282
Note, here we need to use datetime.now(), and we can’t use date.today() because date won’t have the time associated with it.
If you want to subtract minutes, you can just subtract the call to the timedelta() function.
How to Add Minutes to a Date Variable With pandas in Python
If you are using the Python pandas module, we can add minutes to a datetime easily.
With pandas, to add minutes to a datetime, we use the DateOffset() function.
Below is an example of how to use pandas to add minutes to a datetime in Python.
import pandas as pd
startdate = "05/05/2022"
enddate = pd.to_datetime(startdate) + pd.DateOffset(minutes=1)
print(startdate)
print(enddate)
#Output:
2022-05-05 00:00:00
2022-05-05 00:01:00
Hopefully this article has been beneficial for you to learn how to add minutes to a datetime variable in Python.