在python中需要两次相加的帮助/反馈

2024-10-02 00:42:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在做一个关于时钟算法的程序。我的程序要求用户使用两个不同的时间,标准格式和军事时间[HH:MM:SS]。然后我把这两次相加得到最终结果。我需要帮助解决两个问题,我试图解决,但我已经挣扎了很多。在

最后,它应该是这样的: HH:MM:SS+HH:MM:SS=HH:MM:SS 结果完全取决于用户输入的内容

  1. 你能告诉我一种方法,我可以防止时间超过24小时60分60秒吗?这些都是截止时间,如果小时、分钟或秒超过了它们的截止值,那么汇总时间就没有意义了。我想知道怎样才能做到这一点,我想这需要整数除法或模运算符(%)。我将非常感谢你在这里的帮助。我需要把我的时间限制在这些范围内,因为用户可以选择任何可能溢出的时间。在达到这些截止点之后,时间应该重新回到零,并从那里绕过去。

  2. 如何确保我的最后时间保持为[HH:MM:SS]格式?我将非常感谢你的帮助。有时,格式是[H:M:S],这是我不想要的。

我将非常感谢你在这两个问题上的帮助,我正在努力解决。我就快把一切都搞定了。我只需要知道代码,在达到某个限制后,给我一个重新启动的截止时间,以及保持[HH:MM:SS]格式的方法。我的程序代码如下所示。非常感谢你

代码

ClockTime1 = input('Enter clock two timie (in military time) in 
the format HH:MM:SS , it has to be in this format in order to 
function correctly :')
ClockTime2= input('Enter clock one time (in military time) in 
the format HH:MM:SS , it has to be in this format in order to 
function correctly :')
print(ClockTime1.split(':'))
print(ClockTime2.split(':'))
ClockTime1Hours= int((ClockTime1.split(':')[0]))
ClockTime2Hours= int((ClockTime2.split(':')[0]))
ClockTime2Minutes= int((ClockTime2.split(':')[1]))
ClockTime1Seconds= int((ClockTime1.split(':')[2]))
ClockTime2Seconds= int((ClockTime2.split(':')[2]))
print(ClockTime1Hours,'hours for clock 1')
print(ClockTime2Hours,'hours for clock 2')
print(ClockTime1Minutes,'minutes for clock 1')
print(ClockTime2Minutes,'minutes for clock 2')
print(ClockTime1Seconds,'seconds for clock 1')
print(ClockTime2Seconds,'seconds for clock 2')
ClockTime1Hours += ClockTime2Hours
print('sum of clock hours=',ClockTime1Hours)
ClockTime1Minutes += ClockTime2Minutes
print('sum of clock minutes=',ClockTime1Minutes)
ClockTime1Seconds += ClockTime2Seconds
print('sum of clock seconds=',ClockTime1Seconds)

控制台显示的内容:

^{pr2}$

Tags: toinformatfor格式hh时间ss
2条回答

我认为python时间模块可以帮助您

import time

a = "00:00:00 1971"
a = time.mktime(time.strptime(a,"%H:%M:%S %Y"))
ClockTime1 = input('Enter clock two timie (in military time) in the format HH:MM:SS , 
it has to be in this format in order to function correctly :')
ClockTime2= input('Enter clock one time (in military time) in the format HH:MM:SS , 
it has to be in this format in order to function correctly :')
ClockTime1+=" 1971"
ClockTime2+=" 1971"
ClockTime1 = time.mktime(time.strptime(ClockTime1,"%H:%M:%S %Y"))
ClockTime2 = time.mktime(time.strptime(ClockTime2,"%H:%M:%S %Y"))
print(time.strftime("%H:%M:%S", time.localtime(ClockTime1-a+ClockTime2-a+a)))

我想我们可以使用一些内置的日期时间函数,而不是自己计算它们:

from datetime import datetime,timedelta
str_t1="23:00:01"
str_t2="23:00:01"
dt1 = datetime.strptime(str_t1, '%H:%M:%S')
dt2 = datetime.strptime(str_t2, '%H:%M:%S')
dt2_delta=timedelta(hours=dt2.hour, minutes=dt2.minute, seconds=dt2.second)
dt3=dt1+dt2_delta
str_t3=datetime.strftime(dt3,'%H:%M:%S')

str_t3的输出为:

str_t3 '22:00:02'

相关问题 更多 >

    热门问题