需要帮助将总分钟数转换为小时和分钟形式吗

2024-05-12 22:19:04 发布

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

我需要帮助使用余数运算符将其转换为小时和分钟格式。一般来说,我对python和编码比较陌生,因此非常感谢您的帮助。在

#Define the value of our variables 
numberOfEpisodes = 13
minutesPerEpisode = 42

#Calculate the results
totalMinutes = numberOfEpisodes * minutesPerEpisode
equivalency=totalMinutes//minutesPerHour

#Display the output 
print(numberOfEpisodes, 'episodes will take', totalMinutes, 'minutes to watch.') print('This is equivalent to', equivalency)

这就是我目前所拥有的,我可以获得有多少小时,但我不知道如何调整代码,以包括剩余的分钟。在

对不起,如果我说的不太明白,但希望你能理解。在


Tags: oftheto编码value格式运算符print
3条回答

查看datetime模块文档中的timedelta文档。您可以将持续时间创建为以分钟为单位的时间增量,然后当您想要显示它时,可以要求timedelta以您想要的任何格式给出它。您可以使用算术计算来获得小时和分钟,但如果您随后需要使用这些数据来计算日期和时间,例如,要知道如果在09:00开始,节目将在什么时间结束,您将需要执行许多额外的步骤,而不仅仅是使用时间增量。在

使用模运算符%

#Define the value of our variables                                                                                                                                                                                                                                            
numberOfEpisodes = 13
minutesPerEpisode = 42

#Calculate the results                                                                                                                                                                                                                                                        
totalMinutes = numberOfEpisodes * minutesPerEpisode
equivalency=totalMinutes//60
minutes= totalMinutes%60

#Display the output                                                                                                                                                                                                                                                           
print(numberOfEpisodes, 'episodes will take', totalMinutes, 'minutes to watch.')
print('This is equivalent to', equivalency,minutes)

您可以对余数使用//整数除法和%模。(您可以阅读更多关于Python的intfloat除法here

>>> numberOfEpisodes = 13
>>> minutesPerEpisode = 42
>>> totalMinutes = numberOfEpisodes * minutesPerEpisode
>>> totalMinutes
546

>>> minutesPerHour = 60
>>> totalHours = totalMinutes // minutesPerHour
>>> totalHours
9

>>> remainingMinutes = totalMinutes % minutesPerHour
>>> remainingMinutes
6

结果

^{pr2}$

相关问题 更多 >