【问题标题】:Python get hours min and days from the secondsPython 从秒中获取小时分钟和天数
【发布时间】:2020-11-21 04:11:08
【问题描述】:

在 python 中使用我的代码,我从 seconds 中得到 min 。但我也想要 60 分钟后的时间和 24 小时后的天数,我怎样才能让这成为可能,任何人都可以知道。

我的代码如下:

time = int(booking[index]['fields']['google_time'])
time_in_min = time / 60
booking[index]['fields']['google_time_in_min'] = round(time_in_min)

【问题讨论】:

  • booking[index]['fields']['google_time']的值是多少?

标签: python python-3.x django


【解决方案1】:

很简单)

time_in_min = time / 60
time_in_hours = ''
time_in_days = ''
if time_in_min == 60:
    time_in_min = 0
    time_in_hours = 1
if time_in_hours == 24:
    time_in_hours = 0
    time_in_days = 1

等等

【讨论】:

    【解决方案2】:

    根据您的问题,不清楚您希望以哪种格式获得结果,但您可以使用递归函数轻松解决您的问题。我总是会在几秒钟内节省时间,然后对其进行改造。

    您可以添加天、月、年...

    def transform_time(sec):
        if sec < 60:
            return str(sec) + ' sec'
        if 60 < sec < 60*60:
            return str(round(sec/60)) + 'mins :' + str(transform_time(sec % 60))
        if 60*60 < sec < 24*60*60:
            return str(round(sec/60)) + 'hours :' + transform_time(sec)
    
    if __name__ == '__main__':
        print(transform_time(3032))
    

    【讨论】:

      【解决方案3】:

      怎么样:

      
      def work_out_hour_min_sec(total_seconds):
          hours = int(total_seconds / 3600)
          mins = int(total_seconds % 3600 / 60)
          seconds = total_seconds - hours * 3600 - mins * 60
          return hours, mins, seconds
      
      print(work_out_hour_min_sec(3700))
      
      

      可能不是最 Pythonic/优雅的方式,但只需 5 分钟的思考。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 1970-01-01
        • 2011-05-02
        • 2012-01-06
        相关资源
        最近更新 更多