增加时间的最佳方法是什么?

时间:2020-01-21 23:12:37

标签: python datetime python-datetime

我想将用户给定的时间加到另一个时间上,并增加n次

start_time = '7:00' #these values will be taken as string by user
hour_time = '0:30'
increment_var = 5

time_var = datetime.strptime(start_time, '%H:%M')
difference_time = datetime.strptime(hour_time, '%H:%M')

time_var2 = difference_time.time()

尝试过

timed = timedelta(
    hours=time_var2.hour, minutes=time_var2.minute)

for num in range(increment_var):
    diffrence = time_var + timed
    print(diffrence)

它给了我

1900-01-01 07:30:00
1900-01-01 07:30:00
1900-01-01 07:30:00
1900-01-01 07:30:00
1900-01-01 07:30:00

虽然我期望

1900-01-01 07:30:00
1900-01-01 08:00:00
1900-01-01 08:30:00
1900-01-01 09:00:00
1900-01-01 09:30:00

同样的结果

for num in range(increment_var):
    timed = timedelta(hours=time_var2.hour,
                      minutes=time_var2.minute)
    difference = time_var + timed
    print(difference)

2 个答案:

答案 0 :(得分:1)

您能看到下面这段代码为什么起作用吗?

for num in range(increment_var):
    timed = timedelta(hours=time_var2.hour,
                      minutes=time_var2.minute)
    time_var = time_var + timed
    print(time_var)

答案 1 :(得分:1)

您没有在for循环中更新时间

for num in range(increment_var + 1):
    print(time_var)
    time_var += timed