【问题标题】:How to convert a 3 digit number to Minute-Second format如何将 3 位数字转换为分秒格式
【发布时间】:2021-02-08 01:24:43
【问题描述】:

在我的篮球模拟游戏中,刻钟设置为 3 位数,12 分钟刻钟 * 60 秒 = 720 秒。在我的游戏结果之后,我从四分之一时钟中减去一个介于 10 到 24 之间的随机数。我打印我的比赛结果,以及四分之一时钟。 示例代码:

quarter_clock = 12 * 60
time_runoff = random.randint(10,24)

def play():
    if player_makes_shot:
    print("player makes the shot")
    quarter_clock = quarter_clock - time_runoff
    print(quarter_clock)

输出:

player makes shot
702

如何使时钟输出为分秒格式,如下所示:

11:42

感谢您的帮助! :)

【问题讨论】:

  • 将随机时间转换为秒,然后再转换回小时分秒
  • 随机时间以秒为单位。我想知道如何将最终输出转换为分钟和秒。
  • 我是说将你的原始时间全部转换为秒,然后使用函数返回一个包含小时和分钟的元组

标签: python datetime time


【解决方案1】:

您可以使用divmod,它“返回两个数字相除后的商和余数”:

>>> divmod(702,60)
(11, 42)

所以你可以这样做:

>>> minutes, seconds = divmod(702,60)
>>> print(f"{minutes}:{seconds}")
11:42

编辑:

如果是 1 位数字,您还可以在秒的左侧添加 0,例如:

>>> minutes, seconds = divmod(662,60)
>>> print(f"{minutes}:{seconds:02d}")
11:02

【讨论】:

    【解决方案2】:

    我会在这里使用time 库。它正是为此而设计的,您可以输入任何您喜欢的格式:

    所以对于分钟和秒(即12:00),请执行time.strftime("%M:%S", time.gmtime(quarter_clock))

    time.strftime("%M:%S", time.gmtime(702))
    Out[13]: '11:42'
    

    而且只是在打印语句中做一个简单的改动

    import time
    import random
    
    quarter_clock = 12 * 60
    time_runoff = random.randint(10,24)
    
    def play():
        if player_makes_shot:
            print("player makes the shot")
            quarter_clock = quarter_clock - time_runoff
            print(time.strftime("%M:%S", time.gmtime(quarter_clock)) )
    

    【讨论】:

      【解决方案3】:
       def convert(seconds): 
            seconds = seconds % (24 * 3600) 
             hour = seconds // 3600
             seconds %= 3600
             minutes = seconds // 60
             seconds %= 60
            return hour,minutes,seconds
      
       def get_sec(h,m,s):
            """Get Seconds from time."""
           if h==np.empty:
               h=0
           if m==np.empty:
               m=0
           if s==np.empty:
               s=0
           return int(h) * 3600 + int(m) * 60 + int(s)    
      

      【讨论】:

      • 将 0 传递给几小时得到秒数,然后将秒数转换回分秒数,忽略小时数
      猜你喜欢
      • 2023-03-23
      • 1970-01-01
      • 2021-01-28
      • 2011-04-09
      • 1970-01-01
      • 2020-12-13
      • 2013-06-08
      • 1970-01-01
      • 2013-11-11
      相关资源
      最近更新 更多