英文:
Is there any way of preserving the hundredths of seconds with the function "as.ITime" of data.table?
问题
我想将一个类为 "data.table" 的表格中的一列(例如:"01:22:03.56")从字符格式转换为日期格式,使用[data.table]函数 "as.ITime",但在转换后失去了百分之一秒。是否有办法在[data.table]中保留百分之一秒?
英文:
I'd like to transform a column of a table of class "data.table" which is in characters ("01:22:03.56" for example) into date format with the [data.table] function "as.ITime", but I lose the hundredths of seconds after conversion (01:22:03). Is there any way of preserving the hundredths of seconds with [data.table]?
答案1
得分: 0
前言:ITime
的设计是将时间存储为整数。从 ?as.ITime
:
描述:
带有整数存储的日期和时间类,用于快速排序和分组。仍然处于实验阶段!
这意味着使用 as.ITime
没有直接存储毫秒的方式。
选择最佳选项取决于您后续处理的要求。
-
使用
lubridate::hms
,它创建一个"Period"
类的对象。tm <- lubridate::hms("01:22:03.56") tm + 5 # [1] "1H 22M 8.56S" ### 这看起来有点奇怪... tm - 5 # [1] "1H 22M -1.44S" ### ... 但最终可以解决 (tm + 5) - (tm - 5) # [1] "10S"
-
选择一个日期(任意日期),并将其前置到时间,然后使用
as.POSIXct
:tm <- as.POSIXct(paste("1970-01-01", "01:22:03.56")) tm # [1] "1970-01-01 01:22:03 EST" ### 为了证明毫秒在其中,您可以使用以下方式之一 dput(tm) # structure(22923.56, class = c("POSIXct", "POSIXt"), tzone = "") ### 或者您可以设置在控制台上的显示方式 options(digits.secs=3) tm # [1] "1970-01-01 01:22:03.56 EST" tm + 5 # [1] "1970-01-01 01:22:08.56 EST" tm - 5 # [1] "1970-01-01 01:21:58.56 EST"
-
如果您只需要该时间的数字解释,那么
time2num <- function(x) { vapply(strsplit(x, ':'), function(y) sum(as.numeric(y) * c(60*60, 60, 1)), numeric(1), USE.NAMES=FALSE) } tm <- time2num("01:22:03.56") tm # [1] 4923.56
英文:
Up front: ITime
by-design stores as an integer. From ?as.ITime
:
Description:
Date and time classes with integer storage for fast sorting and
grouping. Still experimental!
This means there is no direct way of storing the time with milliseconds using as.ITime
.
Options, which is best depends heavily on what your follow-on processing requires.
-
Use
lubridate::hms
, which creates an object of class"Period"
.tm <- lubridate::hms("01:22:03.56") tm + 5 # [1] "1H 22M 8.56S" ### this will look odd ... tm - 5 # [1] "1H 22M -1.44S" ### ... but it works out in the end (tm + 5) - (tm - 5) # [1] "10S"
-
Pick a date (arbitrary) and prepend it to the time, then use
as.POSIXct
:tm <- as.POSIXct(paste("1970-01-01", "01:22:03.56")) tm # [1] "1970-01-01 01:22:03 EST" ### to prove that milliseconds are in there, you can either dput(tm) # structure(22923.56, class = c("POSIXct", "POSIXt"), tzone = "") ### or you can set how it is rendered on the console options(digits.secs=3) tm # [1] "1970-01-01 01:22:03.56 EST" tm + 5 # [1] "1970-01-01 01:22:08.56 EST" tm - 5 # [1] "1970-01-01 01:21:58.56 EST"
-
If all you need is a numeric interpretation of that time, then
time2num <- function(x) { vapply(strsplit(x, ':'), function(y) sum(as.numeric(y) * c(60*60, 60, 1)), numeric(1), USE.NAMES=FALSE) } tm <- time2num("01:22:03.56") tm # [1] 4923.56
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论