r - 将毫秒列添加到日期时间

标签 r datetime posixct

数据框看起来像

datetime            msec    value 

2022-07-19 17:30:00 8       5   
2022-07-19 17:30:00 58      9   
2022-07-19 17:30:00 108     3   

我想像这样将毫秒添加到日期时间

datetime               value  
2022-07-19 17:30:00.008   5    
2022-07-19 17:30:00.058   9   
2022-07-19 17:30:00.108   3   

我试过了

df$datetime <- as.POSIXct(paste(dfdatetime, df$msec), format="%y/%m/%d %H:%M:%OS")

最佳答案

您需要将其解析为正确的格式才能使其正常工作。这可以通过多种方式完成。

添加毫秒(感谢 @Ritchie Sacramento 的这一点):

new_datetime <- df$datetime + df$msec/1000

或使用lubridate:

new_datetime <- df$datetime + lubridate::milliseconds(df$msec)

按照您自己的方法粘贴它:

但要小心:

  • 在秒和毫秒之间使用.,没有空格(因此paste0)。
  • 日期格式采用 - 而不是 /
  • 用零填充毫秒(感谢 @Ritchie Sacramento 的这一点)
df$new_datetime <- as.POSIXct(paste0(df$datetime, ".", sprintf("%03d", df$msec)), format="%Y-%m-%d %H:%M:%OS")

输出:(会有舍入/表示错误)*

options(digits.secs=3)

df

# A tibble: 3 × 4
  datetime                 msec value new_datetime           
  <dttm>                  <dbl> <dbl> <dttm>                 
1 2022-07-19 17:30:00.000     8     5 2022-07-19 17:30:00.007
2 2022-07-19 17:30:00.000    58     9 2022-07-19 17:30:00.058
3 2022-07-19 17:30:00.000   108     3 2022-07-19 17:30:00.108

或者:将其格式化为显示 3 位数字的毫秒。

format(df$new_datetime, "%Y-%m-%d %H:%M:%OS3")

[1] "2022-07-19 17:30:00.007" "2022-07-19 17:30:00.058" "2022-07-19 17:30:00.108"

数据:

library(readr)

df <- read_delim("datetime,msec,value
2022-07-19 17:30:00,8,5
2022-07-19 17:30:00,58,9
2022-07-19 17:30:00,108,3")

(*) 请参阅Milliseconds in POSIXct Class

更新:修复解析错误。抱歉没有意识到!

关于r - 将毫秒列添加到日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75171238/

相关文章:

r - 如何安装 GDAL 以在 R 中使用 rgdal?

r - 为什么 all.equal 不能在 dplyr 的 mutate 函数中工作?

r - data.table中POSIXct的高效对比

r - POSIXct类中的毫秒

arrays - 数组中的维数和下标数不正确

r - 带有自定义刻度的 GGplot 自定义比例转换

c# 获取 UTC 特定时区的午夜时间

python - Pandas 验证日期格式

python - 在 pandas 中使用混合日期时间格式

r - 在 R 和 Postgres DBMS 之间传递 POSIXct 对象时如何正确处理时区?