【问题标题】:Converting integer numbers to hh:mm:ss in python在python中将整数转换为hh:mm:ss
【发布时间】:2021-09-06 02:08:08
【问题描述】:

我在这样的数据框中有一列数据,这些是小时,但它们并不都包含相同的位数

0,
600,
1200,
1800,
0,
600, 
...

我想将其更改为hh:mm:ss 的格式。我该怎么做?

【问题讨论】:

  • 例如,1800 表示 1800 小时?
  • 我猜他们是秒数。
  • 举例说明它是什么以及你想成为什么样的人
  • @Ma0 是的,午夜,六点,中午,六点等

标签: python pandas datetime time


【解决方案1】:

pandas 版本,使用 zfill 和 wrap:

import pandas as pd

df = pd.DataFrame({'time': [0, 600, 1200, 1800, 0, 600]})

# fill with zeros to always get 4 digits
# split into two parts, with : inbetween
# add the seconds as ':00'
df['hms'] = df['time'].astype(str).str.zfill(4).str.wrap(2).str.replace('\n', ':') + ':00'

df['hms']
0    00:00:00
1    06:00:00
2    12:00:00
3    18:00:00
4    00:00:00
5    06:00:00
Name: hms, dtype: object

【讨论】:

    【解决方案2】:

    datetime library 是你的朋友和盟友。

    import datetime
    
    
    lst = [0, 600, 1200, 1800, 0, 600]
    
    lst = [datetime.time(hour=x//100).strftime("%H:%M:%S") for x in lst]
    # -> ['00:00:00', '06:00:00', '12:00:00', '18:00:00', '00:00:00', '06:00:00']
    

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 2015-08-23
      相关资源
      最近更新 更多