将"hr"转换为"00:00:00";到日期时间"00:00:00" [英] Converting chr "00:00:00" to date-time "00:00:00"
问题描述
My question comes from this question. The question had the following character string.
x <- "2007-02-01 00:00:00"
y <- "02/01/2007 00:06:10"
如果您尝试将此字符串转换为日期类对象,则会发生一些有趣的事情.
If you try to convert this string to date-class object, something funny happens.
这是@nrusell的答案中的一个示例.
This is a sample from @nrusell's answer.
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
留下了以下示例.
As you see, 00:00:00
disappears from the first example. @Richard Scriven left the following example in our discussion using 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
?
Once again, 00:00:00
disappears. Why does R avoid keeping 00:00:00
in date-class object after conversion? How can we keep 00:00:00
?
推荐答案
如果日期的时间部分是午夜,则只是print
会删除精度.这是??strftime
帮助中的文字,特别是format参数:
It is just the print
that remove the precision if the time part of a date is a midnight. This is literlay explained in ??strftime
help, specially the format parameter:
一个字符串.默认值为%Y-%m-%d%H:%M:%S"(如果有) 组件的时间组件不是午夜,而%Y-%m-%d" 否则
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
一个想法是重新定义POSIXct对象的S3方法print
:
One idea is to redefine the S3 method print
for POSIXct object:
print.POSIXct <- function(x,...)print(format(x,"%Y-%m-%d %H:%M:%S"))
现在以您的示例为例,如果您打印x日期(带有午夜部分),您将得到:
Now for your example if your print your x date(with midnight part) you get:
x <- "2007-02-01 00:00:00"
x <- as.POSIXct(x,tz=Sys.timezone())
x
[1] "2007-02-01 00:00:00"
这篇关于将"hr"转换为"00:00:00";到日期时间"00:00:00"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!