【问题标题】:Python timedelta in full days, full hours and so onPython timedelta 全天、全小时等
【发布时间】:2016-04-28 08:55:34
【问题描述】:

我想要一些如何打印消息,例如: “从那时起,已经过去了 x 天、y 小时、z 分钟和 w 秒”。 目前我正在做这样的事情,但我想念其余部分加上(最重要的是)我不喜欢它。应该有更美的东西

dt = (datetime.now() - datetime(year=1980, month=1, day=1, hour=18)).total_seconds()
full_days = int(dt // (3600 * 24))
full_hours = int((dt - full_days * (24 * 3600)) // 3600)
full_minutes = int((dt - full_days * (24 * 3600) - full_hours * 3600) // 60)
residual_seconds = dt - full_days * (24 * 3600) - full_hours * 3600 - full_minutes * 60
print(full_days, full_hours, full_minutes, residual_seconds)

【问题讨论】:

    标签: python datetime timedelta


    【解决方案1】:

    你可以使用timedelta:

    from datetime import datetime
    
    fmt = 'Since then, {0} days, {1} hours, {2} minutes and {3} seconds have elapsed'
    td = datetime.now() - datetime(year=1980, month=1, day=1, hour=18)
    print(fmt.format(td.days, td.seconds // 3600, td.seconds % 3600 // 60, td.seconds % 60))
    

    输出:

    Since then, 13266 days, 23 hours, 5 minutes and 55 seconds have elapsed
    

    【讨论】:

      【解决方案2】:

      试试这个,希望对你有用:

      import datetime
      from dateutil.relativedelta import relativedelta
      
      end = '2016-01-01 12:00:00'
      begin = '2015-03-01 01:00:00'
      
      start = datetime.datetime.strptime(end, '%Y-%m-%d %H:%M:%S')
      ends = datetime.datetime.strptime(begin, '%Y-%m-%d %H:%M:%S')
      
      diff = relativedelta(start, ends)
      
      print "%d year %d month %d days %d hours %d minutes" % (diff.years, diff.months, diff.days, diff.hours, diff.minutes)
      

      输出:

      0 year 10 month 0 days 11 hours 0 minutes   
      

      【讨论】:

        【解决方案3】:

        Humanize可以将各种数据转换成人类可读的格式。

        >>> import humanize
        >>> from datetime import datetime, timedelta
        >>> humanize.naturaltime(datetime.now() - timedelta(seconds=3600))
        'an hour ago'
        

        【讨论】:

          【解决方案4】:

          这可能被认为更漂亮,但我不确定它是否真的是 Pythonic。就我个人而言,我只是隐藏函数中的“丑陋”代码。总之,

          dt=datetime(2016,1,2,11,30,50)-datetime(2016,1,1)
          
          s=dt.total_seconds()
          
          t=[]
          for x in (24*3600,3600,60,1):
             t.append(s//x)
             s -= t[-1]*x
          
          days,hours,mins,secs=t
          
          >>> print(t)
          [1.0, 11.0, 30.0, 50.0]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-10-13
            • 2011-01-08
            • 2016-08-22
            • 1970-01-01
            • 2016-02-27
            • 2020-12-14
            • 2020-10-13
            • 1970-01-01
            相关资源
            最近更新 更多