You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

lubridate解析带小数的'MS'格式时间为何多1秒?

Weird Second Rounding with parse_date_time for Decimal Times

Hey there, let's break down this confusing behavior you're hitting with lubridate's parse_date_time function.

First, let's recap what you're seeing:

  • When parsing '5:55' with the format 'MS', everything works as expected: second(time) returns 55.
  • But add a decimal (like '5:55.34'), and suddenly second(time) spits out 56.34 instead of 55.34—total head-scratcher, right?

Is this expected behavior?

Short answer: No, this is a bug that existed in older lubridate versions (1.7.x, which you're using across Windows and Mac). It's not intended behavior—you shouldn't see the integer part of the seconds getting rounded up just because you added a decimal.

Why does this happen?

The issue stems from how the parse_date_time function handled decimal seconds in those older versions. The parser had a quirk where, when using the 'MS' format specifier, it misinterpreted the decimal portion and incorrectly incremented the integer second value by 1. This was fixed in later versions of lubridate (starting around 1.8.0).

How to fix it?

You've got a couple solid options:

  • Upgrade lubridate to the latest version
    This is the most straightforward fix. The bug was squashed in newer releases, so updating should resolve the issue immediately. Run this in your R console:

    install.packages("lubridate")
    

    After upgrading, parsing '5:55.34' with 'MS' will correctly return 55.34 for the seconds.

  • Use a more explicit format string (if you can't upgrade right now)
    Instead of relying on the 'MS' shorthand, use a format that explicitly tells the parser what to expect. For minutes and seconds with decimals, '%M:%OS' works perfectly:

    time <- parse_date_time('5:55.34', '%M:%OS')
    second(time) # Returns 55.34 as expected
    

    Alternatively, lubridate's hm() function is designed for hour-minute-second strings and handles decimals correctly even in older versions:

    time <- hm('5:55.34')
    second(time) # Also returns 55.34
    

Since you're seeing this across Windows and Mac with the same 1.7.x versions, that confirms it's version-specific, not system-specific. Upgrading should fix it everywhere.

内容的提问来源于stack exchange,提问作者Max Candocia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:55:29