Convert chr "00:00:00" to date "00:00:00"

My question comes from this question . The question had the following line of characters.

x <- "2007-02-01 00:00:00" y <- "02/01/2007 00:06:10" 

If you try to convert this string to a date class object, something funny will happen.

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 can see, 00:00:00 disappears from the first example. @Richard Scriven posted 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" 

Again 00:00:00 disappears. Why does not R save 00:00:00 in a date class object after conversion? How can we save 00:00:00 ?

+5
source share
2 answers

Only print removes precision if the time part of the date is midnight. This is explained in the help of ??strftime , especially the format parameter:

Character string The default value is "% Y-% m-% d% H:% M:% S" if it has a time component that is not midnight, and "% Y-% m-% d" otherwise

One idea is to override the S3 print method for the POSIXct object:

 print.POSIXct <- function(x,...)print(format(x,"%Y-%m-%d %H:%M:%S")) 

Now for your example, if you print your date x (with midnight), you get:

 x <- "2007-02-01 00:00:00" x <- as.POSIXct(x,tz=Sys.timezone()) x [1] "2007-02-01 00:00:00" 
+5
source

This question is too old, but still I want to connect my answer with this question to this question:

Link: fooobar.com/questions/16719838 / ...

0
source

Source: https://habr.com/ru/post/1203098/


All Articles