【问题标题】:How to convert 4-digit number into hours:minutes time format in pandas如何在熊猫中将 4 位数字转换为小时:分钟时间格式
【发布时间】:2017-09-05 04:55:30
【问题描述】:

我有一个由小时和分钟组成的 4 位字符串格式的时间。 例如 1608 需要转换为 => 16:08

数据是pandas数据框的形式,我试过了:

     A    st_time
1    23   1608
2    12   1635
3    18   1654
4    38   1705

我尝试使用:

df.st_time.to_datetime().strftime('%h-%m') 

但是,它会引发错误。

AttributeError: 'Series' object has no attribute 'to_datetime'

【问题讨论】:

    标签: python pandas datetime time


    【解决方案1】:

    先将数字转换为字符串,然后使用indexing with str:

    df.st_time = df.st_time.astype(str)
    df.st_time = df.st_time.str[:2] + ':' + df.st_time.str[-2:]
    print (df)
        A st_time
    1  23   16:08
    2  12   16:35
    3  18   16:54
    4  38   17:05
    

    【讨论】:

    • 解决方案有问题?
    • 35:16 小时代替了分钟!
    • 35:16 的期望输出是什么?
    【解决方案2】:

    您需要通过将系列df.st_time 传递给它来使用pd.to_datetime。完成后,您可以访问time 组件。

    df.assign(newtime=pd.to_datetime(df.st_time, format='%H%M').dt.time)
    
        A  st_time   newtime
    1  23     1608  16:08:00
    2  12     1635  16:35:00
    3  18     1654  16:54:00
    4  38     1705  17:05:00
    

    但是,如果您想要返回指定格式的字符串。

    df.assign(newtime=pd.to_datetime(df.st_time, format='%H%M').dt.strftime('%H:%M'))
    
        A  st_time newtime
    1  23     1608   16:08
    2  12     1635   16:35
    3  18     1654   16:54
    4  38     1705   17:05
    

    【讨论】:

    • 它适用于一个小数据框,但由于我的数据框有 17m 行,所以每次我尝试执行它时它都会冻结。
    猜你喜欢
    • 2018-10-27
    • 2015-09-22
    • 1970-01-01
    • 2019-09-26
    • 2017-04-13
    • 2023-03-22
    • 2013-11-11
    • 2023-02-06
    • 2020-08-15
    相关资源
    最近更新 更多