Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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" 

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"

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?

like image 943
jazzurro Avatar asked Sep 21 '14 22:09

jazzurro


1 Answers

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:

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

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"))

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"
like image 155
agstudy Avatar answered Sep 20 '22 21:09

agstudy