如何在Python中将时间添加到 DateTime 对象上
在本文中,我们将讨论在Python向指定的 DateTime 对象添加时间。这样做的效果将产生一个新的 DateTime 对象。可以通过使用执行此添加 datetime.timedelta()函数。 timedelta()函数用于计算日期差异,也可用于Python的日期操作。这是执行日期操作的最简单方法之一。
Syntax: datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Return values: This function returns the manipulated date.
因此,通过简单地将适当的值传递给上述给定的参数,就可以实现所需的任务。
示例 1:向 DateTime 对象添加时间
Python3
# Python3 code to illustrate the addition
# of time onto the datetime object
# Importing datetime
import datetime
# Initializing a date and time
date_and_time = datetime.datetime(2021, 8, 22, 11, 2, 5)
print("Original time:")
print(date_and_time)
# Calling the timedelta() function
time_change = datetime.timedelta(minutes=75)
new_time = date_and_time + time_change
# Printing the new datetime object
print("changed time:")
print(new_time)
Python3
# Python3 code to illustrate the addition
# of time onto the datetime object
# Importing datetime
import datetime
# Initializing a date and time
date_and_time = datetime.datetime(2021, 8, 22, 11, 2, 5)
print("Original time:")
print(date_and_time)
# Calling the timedelta() function
time_change = datetime.timedelta(hours=36)
new_time = date_and_time + time_change
# Printing the new datetime object
print("changed time:")
print(new_time)
Python3
# Python3 code to illustrate the addition
# of time onto the datetime object
# Importing datetime
import datetime
# Initializing a date and time
date_and_time = datetime.datetime(2021, 8, 22, 11, 2, 5)
print("Original time:")
print(date_and_time)
# Calling the timedelta() function and
# adding 2 minutes and 10 seconds
time_change = datetime.timedelta(minutes=2, seconds=10)
new_time = date_and_time + time_change
# Printing the new datetime object
print("changed time:")
print(new_time)
输出:
Original time:
2021-08-22 11:02:05
changed time:
2021-08-22 12:17:05
示例 2:通过向 DateTime 添加时间来更改日期
蟒蛇3
# Python3 code to illustrate the addition
# of time onto the datetime object
# Importing datetime
import datetime
# Initializing a date and time
date_and_time = datetime.datetime(2021, 8, 22, 11, 2, 5)
print("Original time:")
print(date_and_time)
# Calling the timedelta() function
time_change = datetime.timedelta(hours=36)
new_time = date_and_time + time_change
# Printing the new datetime object
print("changed time:")
print(new_time)
输出:
Original time:
2021-08-22 11:02:05
changed time:
2021-08-23 23:02:05
示例 3:同时更改两个参数
蟒蛇3
# Python3 code to illustrate the addition
# of time onto the datetime object
# Importing datetime
import datetime
# Initializing a date and time
date_and_time = datetime.datetime(2021, 8, 22, 11, 2, 5)
print("Original time:")
print(date_and_time)
# Calling the timedelta() function and
# adding 2 minutes and 10 seconds
time_change = datetime.timedelta(minutes=2, seconds=10)
new_time = date_and_time + time_change
# Printing the new datetime object
print("changed time:")
print(new_time)
输出:
Original time:
2021-08-22 11:02:05
changed time:
2021-08-22 11:04:15