【问题标题】:How to convert timedelta to hours如何将 timedelta 转换为小时
【发布时间】:2020-05-30 14:03:45
【问题描述】:

我有一个 timedelta 数据框

JC time
1 3days 21:02:05
2 1days 23:50:07
3 6days 19:28:36

但我想要

1 93:02:05
2 47:50:07
3 163:28:36

如何转换?

【问题讨论】:

  • 您可能会查看日期时间库。发布一些代码的工作尝试,这将有所帮助。

标签: python pandas dataframe timedelta


【解决方案1】:

使用,pd.to_timedeltaSeries.dt.componentsDataFrame.agg & Series.str.zfill的组合:

d = pd.to_timedelta(df['time']).dt.components[['days', 'hours', 'minutes', 'seconds']]
d['hours'] = d['hours'].add(d.pop('days') * 24)

df['time'] = d.astype(str).agg(lambda s: ':'.join(s.str.zfill(2)), axis=1)

结果:

# print(df)

   JC       time
0   1   93:02:05
1   2   47:50:07
2   3  163:28:36

【讨论】:

    【解决方案2】:

    您可以执行以下操作将timedelta 转换为所需格式的小时数、分钟数和秒数:

    def convert_to_hours(delta):
        total_seconds = delta.total_seconds()
        hours = str(int(total_seconds // 3600)).zfill(2)
        minutes = str(int((total_seconds % 3600) // 60)).zfill(2)
        seconds = str(int(total_seconds % 60)).zfill(2)
        return f"{hours}:{minutes}:{seconds}"
    
    delta = timedelta(days=3, hours=21, minutes=2, seconds=5)
    # 3 days, 21:02:05
    
    convert_to_hours(delta)
    # 93:02:05
    

    要转换您的数据框,您可以执行以下操作:

    df["time"] = df["time"].apply(convert_to_hours)
    

    【讨论】:

      【解决方案3】:

      这是另一种方法:

      def strf_delta(td):
          h, r = divmod(int(td.total_seconds()), 60*60)
          m, s = divmod(r, 60)
          h, m, s = (str(x).zfill(2) for x in (h, m, s))
          return f"{h}:{m}:{s}"
      
      d['time'].apply(strf_delta)
      

      【讨论】:

      • 美观易读;您可以使用 f 字符串中整数的格式代码保存另一行:return f"{h:02d}:{m:02d}:{s:02d}"
      猜你喜欢
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 2023-01-05
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      相关资源
      最近更新 更多