Home > front end >  Displaying datetime at midnight as datetime, not as date using R
Displaying datetime at midnight as datetime, not as date using R

Time:11-09

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)

CodePudding user response:

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
  • Related