【问题标题】:How to convert duration strings to seconds?如何将持续时间字符串转换为秒?
【发布时间】:2022-01-27 21:31:21
【问题描述】:

我在 pandas 数据框中有这样一列:

duration
1 day 22:12:15.778543
2 days 10:09:07.118723
00:18:23.985112

我想将此duration 转换为秒。

我该怎么做?我不确定这是否可能,因为我得到了特殊的字符串格式(1 day2 days 等)?

【问题讨论】:

    标签: pandas datetime time strptime


    【解决方案1】:

    to_timedeltaSeries.dt.total_seconds 一起使用:

    df['s'] = pd.to_timedelta(df['duration']).dt.total_seconds()
    print (df)
                     duration              s
    0   1 day 22:12:15.778543  166335.778543
    1  2 days 10:09:07.118723  209347.118723
    2         00:18:23.985112    1103.985112
        
    

    【讨论】:

    • 替代df['seconds'] = pd.TimedeltaIndex(df['duration']).total_seconds()
    • @Corralien - 是的,可能的解决方案。但我更喜欢Series 的解决方案,而不是Index
    • 非常感谢@jezrael!没想到这么简单。
    猜你喜欢
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 2012-05-26
    • 2016-11-05
    相关资源
    最近更新 更多