MrXsquared
MrXsquared

Reputation: 185

Displaying datetime at midnight as datetime, not as date using R

I have two variables in R, lets say for example:

from <- as.POSIXct('2022-06-25 00:00:00', format="%Y-%m-%d %H:%M:%S",tz='UTC')

and

to <- as.POSIXct('2022-06-25 14:00:00', format="%Y-%m-%d %H:%M:%S",tz='UTC')

I want to display! both in datetime format, e.g. in a dataframe or in my variable-environment in R studio or when exporting this value as csv or xlsx. The second one to always displays correct as its not at midnight, but the first one from always displays as 2022-06-25, so as a date, but not as datetime. Calculations are correct, so its just a display issue. How can I force R to display this value including time? Minimal example:

from <- as.POSIXct('2022-06-25 00:00:00', format="%Y-%m-%d %H:%M:%S",tz='UTC')
to <- as.POSIXct('2022-06-25 14:00:00', format="%Y-%m-%d %H:%M:%S",tz='UTC')
data <- data.frame(x1 = 1:5)
data <- cbind(to = to, data)
data <- cbind(from = from, data)
data 
view(data)

Upvotes: 0

Views: 515

Answers (1)

Julian_Hn
Julian_Hn

Reputation: 2141

We can use format to force arbitrary display formats for POSIXct or POSIXt vectors:

format(data,format="%Y-%m%-%d %T")
                 from                  to x1
1 2022-06-25 00:00:00 2022-06-25 14:00:00  1
2 2022-06-25 00:00:00 2022-06-25 14:00:00  2
3 2022-06-25 00:00:00 2022-06-25 14:00:00  3
4 2022-06-25 00:00:00 2022-06-25 14:00:00  4
5 2022-06-25 00:00:00 2022-06-25 14:00:00  5

Unfortunately AFAICS there is no default way to make this, but you can write a custom print function that does this:

print_with_time <- function(df, ...)
{
  df <- data
  timeCols <- which(sapply(df,inherits,"POSIXt"))
  for(i in timeCols)
  {
    df[[i]] <- format(df[[i]],format="%Y-%m-%d %T")
  }
  base::print.data.frame(df, ...)
}

> print_with_time(data)
                 from                  to x1
1 2022-06-25 00:00:00 2022-06-25 14:00:00  1
2 2022-06-25 00:00:00 2022-06-25 14:00:00  2
3 2022-06-25 00:00:00 2022-06-25 14:00:00  3
4 2022-06-25 00:00:00 2022-06-25 14:00:00  4
5 2022-06-25 00:00:00 2022-06-25 14:00:00  5

Now, if you really want that to happen by just calling print on a data.frame you can overwrite the default S3 method dispatch target print.data.frame with this function. But beware this might lead to unexpected results elsewhere:

print.data.frame <- print_with_time
> print(data)
                 from                  to x1
1 2022-06-25 00:00:00 2022-06-25 14:00:00  1
2 2022-06-25 00:00:00 2022-06-25 14:00:00  2
3 2022-06-25 00:00:00 2022-06-25 14:00:00  3
4 2022-06-25 00:00:00 2022-06-25 14:00:00  4
5 2022-06-25 00:00:00 2022-06-25 14:00:00  5

Upvotes: 1

Related Questions