R/POSIX控制结果格式(秒、分钟、小时)

R/POSIX控制结果格式(秒、分钟、小时),r,datetime,posixct,R,Datetime,Posixct,我正在使用R中的一些POSIXct对象,想知道如何控制答案的格式 train$targetVar1 <- as.numeric(as.POSIXct(as.character(string1),tz="UTC") - as.POSIXct(as.character(string2),tz="UTC")) 有什么建议吗 注意:我正在windows 7计算机上运行R2.15.1。您可以使用格式: x <- as.POSIXlt("2012-12-12") format(x, "%s"

我正在使用R中的一些
POSIXct
对象,想知道如何控制答案的格式

train$targetVar1 <- as.numeric(as.POSIXct(as.character(string1),tz="UTC") - as.POSIXct(as.character(string2),tz="UTC"))
有什么建议吗


注意:我正在windows 7计算机上运行R2.15.1。

您可以使用
格式

x <- as.POSIXlt("2012-12-12")

format(x, "%s")    
[1] "1355266800"

x您可以使用
格式

x <- as.POSIXlt("2012-12-12")

format(x, "%s")    
[1] "1355266800"

x
POSIXct
POSIXlt
对象非常不同。您可以使用
dput
看到这一点:

dput(Sys.time())
structure(1356100378.30553, class = c("POSIXct", "POSIXt"))

dput(as.POSIXlt(Sys.time()))
structure(list(sec = 13.2815599441528, min = 33L, hour = 14L, 
    mday = 21L, mon = 11L, year = 112L, wday = 5L, yday = 355L, 
    isdst = 0L), .Names = c("sec", "min", "hour", "mday", "mon", 
"year", "wday", "yday", "isdst"), class = c("POSIXlt", "POSIXt"
), tzone = c("", "GMT", "BST"))
POSIXct
是自UNIX纪元以来记录秒数的工具,您可以使用
as.numeric
unclass
获得秒数:

as.numeric(Sys.time())
[1] 1356100510
unclass(Sys.time())
[1] 1356100516
请注意,结果的差异是因为我花了6秒钟调用第二个命令

至于您最初的问题,
-.POSIXt
最终调用了
difftime
,它有一个默认的
units
参数
auto
。这意味着输出单位将取决于差异的大小。要获得一致性,请直接调用
difftime

difftime(as.POSIXct(as.character(string1),tz="UTC"), as.POSIXct(as.character(string2),tz="UTC")), units="secs")

POSIXct
POSIXlt
对象非常不同。您可以使用
dput
看到这一点:

dput(Sys.time())
structure(1356100378.30553, class = c("POSIXct", "POSIXt"))

dput(as.POSIXlt(Sys.time()))
structure(list(sec = 13.2815599441528, min = 33L, hour = 14L, 
    mday = 21L, mon = 11L, year = 112L, wday = 5L, yday = 355L, 
    isdst = 0L), .Names = c("sec", "min", "hour", "mday", "mon", 
"year", "wday", "yday", "isdst"), class = c("POSIXlt", "POSIXt"
), tzone = c("", "GMT", "BST"))
POSIXct
是自UNIX纪元以来记录秒数的工具,您可以使用
as.numeric
unclass
获得秒数:

as.numeric(Sys.time())
[1] 1356100510
unclass(Sys.time())
[1] 1356100516
请注意,结果的差异是因为我花了6秒钟调用第二个命令

至于您最初的问题,
-.POSIXt
最终调用了
difftime
,它有一个默认的
units
参数
auto
。这意味着输出单位将取决于差异的大小。要获得一致性,请直接调用
difftime

difftime(as.POSIXct(as.character(string1),tz="UTC"), as.POSIXct(as.character(string2),tz="UTC")), units="secs")

您希望您的示例
作为.POSIXlt(“2012-12-12”)
得到哪一个结果?@SvenHohenstein:对于posixObj1$sec,我希望从1970年1月1日起有几秒的时间。这在R-2.15.2上对我有效(也许这是2.15.1中的一个bug?)。另外,
POSIXlt
hour元素被命名为
hour
,而不是
hr
@JoshuaUlrich:感谢您指出这一点。当我切换到hour时,向量似乎只是保存时间段。我假设他们正在将秒数转换为分、小时等。你希望你的示例的结果是什么?
as.POSIXlt(“2012-12-12”)
?@SvenHohenstein:对于posixObj1$sec,我希望从1970年1月1日开始的秒数。这对我来说在R-2.15.2上有效(也许这是2.15.1中的一个bug?)。另外,
POSIXlt
hour元素被命名为
hour
,而不是
hr
@JoshuaUlrich:感谢您指出这一点。当我切换到hour时,向量似乎只是保存时间段。我以为他们在把秒转换成分钟、小时等。这对我不起作用。请参见编辑问题。我只得到两个引号,它们之间没有任何内容。这对我不适用。请参见编辑问题。我只得到两个引号,它们之间什么都没有。这就是我要找的。非常感谢。还有有用的
单位(x),这正是我想要的。非常感谢。还有有用的
单位(x)