📅  最后修改于: 2023-12-03 15:18:54.594000             🧑  作者: Mango
Python's datetime
module provides various classes to work with date and time values, one of them being the datetime
class. In this tutorial, we will discuss how to add minutes to a datetime value in Python.
To add minutes to a datetime value, we can use the timedelta
class from the datetime
module. The timedelta
class represents a duration or difference between two dates or times.
To add minutes to a datetime object, we can create a timedelta object with the number of minutes and add it to the datetime object using the +
operator.
import datetime
# create a datetime object
dt = datetime.datetime(2022, 1, 1, 12, 0, 0)
# create a timedelta object with 30 minutes
td = datetime.timedelta(minutes=30)
# add 30 minutes to datetime object
new_dt = dt + td
print(f"Original Datetime: {dt}")
print(f"New Datetime: {new_dt}")
Output:
Original Datetime: 2022-01-01 12:00:00
New Datetime: 2022-01-01 12:30:00
In the above example, we first created a datetime object representing January 1, 2022, at 12:00:00. Then we created a timedelta object with 30 minutes and added it to the datetime object using the +
operator. The resulting datetime object represents January 1, 2022, at 12:30:00.
To add minutes to the current datetime value, we can use the now()
method from the datetime
module to get the current datetime object and add the minutes using the timedelta
class.
import datetime
# get current datetime object
now = datetime.datetime.now()
# create a timedelta object with 10 minutes
td = datetime.timedelta(minutes=10)
# add 10 minutes to current datetime object
new_now = now + td
print(f"Current Datetime: {now}")
print(f"New Datetime: {new_now}")
Output:
Current Datetime: 2022-04-25 10:30:00.123456
New Datetime: 2022-04-25 10:40:00.123456
In the above example, we first used the now()
method to get the current datetime object. Then we created a timedelta object with 10 minutes and added it to the current datetime object using the +
operator. The resulting datetime object represents 10 minutes ahead of the current datetime value.
In this tutorial, we learned how to add minutes to a datetime value in Python using the timedelta
class. We also saw how to add minutes to the current datetime value using the now()
method. With this knowledge, you can easily perform date and time calculations in your Python programs.