【问题标题】:Need help converting total number of minutes into hour and minute format需要帮助将总分钟数转换为小时和分钟格式
【发布时间】:2014-10-21 14:08:07
【问题描述】:

我需要使用余数运算符将其转换为小时和分钟格式的帮助。总的来说,我对 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)

这是我目前拥有的,我能够获得有多少小时,但我不知道如何调整代码以包含剩余的分钟数。

对不起,如果我没有充分理解,但希望你能理解。

【问题讨论】:

  • 提示:在编程中,“余数”通常有不同的名称:“模数”。这可能会对您的研究有所帮助。

标签: python python-3.x integer divide


【解决方案1】:

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

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

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

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

结果

>>> print('{} episodes will take {}h {}m to watch.'.format(numberOfEpisodes,totalHours, remainingMinutes))
13 episodes will take 9h 6m to watch.

【讨论】:

  • +1。由于OP是一个新程序员,您可能希望解释真正除法和地板(整数)除法之间的区别。或链接到一些文档。
  • 非常感谢 Cyber​​,现在一切正常。希望您不介意,如果我以后也需要我再次寻求您的帮助。
【解决方案2】:

使用模运算符 %

#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)

【讨论】:

  • 给所有回答的人,非常感谢。非常感谢所有帮助。现在我正在用我的导师给我的教科书练习,但它没有任何答案,所以不幸的是,当我被卡住时,我没有参考使用。所以如果我在很短的时间内问了很多问题,希望大家不要介意。
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 2019-02-22
    • 1970-01-01
    • 2015-07-20
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 2012-01-23
    • 2018-05-04
    相关资源
    最近更新 更多