【问题标题】:Convert minutes to full hours without days将分钟转换为无天的整小时
【发布时间】:2022-01-02 22:28:45
【问题描述】:

对于重型机械,人们通常需要知道一台机器运行了多少小时。我有一个包含开始时间和结束时间的数据框。每次使用机器时,我都会计算机器使用的分钟数。这会产生一列df['minutes']

如何将分钟转换为小时? 3,346 分钟,我应该得到 55 小时 46 分钟,或者55:46

将此作为工作示例:

df = pd.DataFrame(columns = ['minutes'], data =[3346])
  • 如果我使用它,我会得到07:46

      df['duration'] = pd.to_datetime(df['minutes'], unit='m').dt.strftime('%H:%M')
    
  • 如果我使用它,我会得到03 07:46 07:46

      df['duration'] = pd.to_datetime(df['minutes'], unit='m').dt.strftime('%d %H:%M')
    

    为什么是三个 (03)?

  • 我还尝试对分钟列使用 apply 和 gmtime,返回 03 07:46

      def dur_time1(x):
          x*=60
          x = time.gmtime(x)
          x = time.strftime("%d %H:%M", x)
          return x
    
      df['duration'] = df['minutes'].apply(dur_time1)
    
  • 最后,我尝试使用 apply 和 timedelta 到分钟列,返回2 days 07:46:00

      def dur_time2(x):
          x*=60
          x = timedelta(seconds = x)
          return x
    
      df['duration'] = df['minutes'].apply(dur_time2)
    

    我可以忍受 2 天,我可以将其拆分并乘以 24。但这似乎很复杂。

但这些解决方案都没有显示 55 小时 46 分钟。

【问题讨论】:

  • 不是你的问题,只是你的函数写得不好。不要一直覆盖参数,给参数和变量起有意义的名字。第二个可能是def calculate_duration(minutes): return timedelta(seconds=minutes * 60),然后很清楚发生了什么以及为什么。但是,从分钟计算总小时数是微不足道的,您不需要导入任何模块 - 它是 minutes // 60 小时和 minutes % 60 分钟。

标签: python pandas datetime


【解决方案1】:

你可以使用这个功能:

def minutes_to_hours(minutes : int):
    time = '{}:{}'.format(minutes//60,minutes%60)
    return time 

输出:

55:46

【讨论】:

  • f-string 似乎更适合 2022 年:f'{minutes//60}:{minutes%60}'
【解决方案2】:

divmod 也是一个选项:

def minutes_to_hours(minutes: int):
    return '{}:{}'.format(*divmod(minutes,60))

【讨论】:

  • 也应该更快(2 个调用 vs 1 个)
【解决方案3】:

您的结果绝对没有问题。 Python 做了你想做的事。

案例1:你让python给你时间组件中的小时和分钟。

df['duration'] = pd.to_datetime(df['minutes'], unit='m').dt.strftime('%H:%M')

案例 2:您要求 python 在时间组件中为您提供天、小时和分钟。

pd.to_datetime(df['minutes'], unit='m').dt.strftime('%d %H:%M')

从文档%d 执行以下操作;

python 是一个 C 编译器。在 C tm_mday 中,从 1 开始查找下/前几天。简单地说;

strftime() takes an
       argument of data type time_t, which represents calendar time.
       When interpreted as an absolute time value, it represents the
       number of seconds elapsed since the Epoch, 1970-01-01 00:00:00
       +0000 (UTC)

在您的情况下,因为您在这个时间组件中有55.766667 hours,所以strftime('%d %H:%M') 将其解释为3rd day, 7th Hour 46th Minute since the Epoch, 1970-01-01 00:00:00 +0000 (UTC)。如果你把它改成pd.to_datetime(df['minutes'], unit='m').dt.strftime('%d %I:%M'),你会发现它用0填充。

如果您想找到确切的时间分量计数,请使用numpy's Datetime Units

df['minutes'].astype('timedelta64[m]')/60

如上所述,numpy 的日期时间单位中的时间跨度是 64 位整数乘以日期或单位长度的范围。那是时间span for ‘D’ (day) is exactly 24 times longer than the time span for ‘h’ (hour) 条件它将分钟转换为精确的时间分量

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    相关资源
    最近更新 更多