【问题标题】:Python: Round time (without date) to the nearest secondPython:将时间(无日期)舍入到最接近的秒数
【发布时间】:2021-10-09 00:06:31
【问题描述】:

我不断看到这个问题的日期时间案例,但没有一个只是时间。

我有一个这样的时间列:

0   16:19:01.600000
1   16:20:02.700000
2          16:20:18
3   16:21:03.400000
4   16:21:49.200000

为了将时间四舍五入到秒,所以它是 16:19:02、16:20:03 等等,我尝试首先使用以下代码将时间列转换为日期时间:

# Converting time to datetime (again)
pd.to_datetime(trip_28["time"], format="%H:%M:%S")

返回:

unconverted data remains: .600000

那么本意就是使用:

# Rounding the time column to seconds
trip_28["time"] = trip_28["time"].dt.floor('1s')

我怎样才能做到这一点?

【问题讨论】:

  • 将其转换为 timedelta 对我来说更有意义,而不是答案所暗示的实际日期:pd.to_timedelta(df["time"]).dt.round('1s')

标签: python pandas dataframe datetime python-datetime


【解决方案1】:

尝试pd.DatetimeIndex.round,将频率设置为S

来自文档

pd.Series(rng).dt.round("H")
0   2018-01-01 12:00:00
1   2018-01-01 12:00:00
2   2018-01-01 12:00:00

【讨论】:

  • 我认为freq参数应该是“S”,而不是“H”
  • 我就是这么说的。该示例来自文档以显示舍入
【解决方案2】:

转换为日期时间并使用freq='S'进行舍入:

>>> pd.to_datetime(df['Date']).dt.round(freq='S')
0   2021-08-03 16:19:02
1   2021-08-03 16:20:03
2   2021-08-03 16:20:18
3   2021-08-03 16:21:03
4   2021-08-03 16:21:49
Name: Date, dtype: datetime64[ns]

【讨论】:

    猜你喜欢
    • 2018-05-27
    • 1970-01-01
    • 2014-04-07
    • 2021-12-16
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    相关资源
    最近更新 更多