我的问题来自 this question .问题具有以下字符串。
x <- "2007-02-01 00:00:00"
y <- "02/01/2007 00:06:10"
如果您尝试将此字符串转换为日期类对象,则会发生一些有趣的事情。
这是来自@nrusell 答案的示例。
as.POSIXct(x,tz=Sys.timezone())
[1] "2007-02-01 EST"
as.POSIXct(y,format="%m/%d/%Y %H:%M:%S",tz=Sys.timezone())
[1] "2007-02-01 00:06:10 EST"
如您所见,
00:00:00
从第一个例子中消失。 @Richard Scriven 在我们的讨论中使用 lubridate
留下了以下示例.dt <- as.POSIXct("2007-02-01 00:00:00")
hour(dt) <- hour(dt)+1
dt
[1] "2007-02-01 01:00:00 EST"
hour(dt) <- hour(dt)-1
dt
[1] "2007-02-01 EST"
再次,
00:00:00
消失。为什么 R 避免保留 00:00:00
在转换后的日期类对象中?怎样才能保持00:00:00
?
最佳答案
这只是 print
如果日期的时间部分是午夜,则删除精度。这是在 ??strftime
中解释的 literlay帮助,特别是格式参数:
A character string. The default is "%Y-%m-%d %H:%M:%S" if any component has a time component which is not midnight, and "%Y-%m-%d" otherwise
一种想法是重新定义 S3 方法
print
对于 POSIXct 对象:print.POSIXct <- function(x,...)print(format(x,"%Y-%m-%d %H:%M:%S"))
现在以您的示例为例,如果您打印 x 日期(带有午夜部分),您会得到:
x <- "2007-02-01 00:00:00"
x <- as.POSIXct(x,tz=Sys.timezone())
x
[1] "2007-02-01 00:00:00"
关于r - 将 chr "00:00:00"转换为日期时间 "00:00:00",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25964504/