0

This looks like trivial issue but I couldn't make it work. I need simply convert midnight into POSIXct format but also with hours, minutes and seconds, just like that:

nextDay_t <- strptime(paste0(as.character(Sys.Date() + 1)," 00:00:00"), format = "%Y-%m-%d %H:%M:%S")
nextDay_t <- format(nextDay_t, "%Y-%m-%d %H:%M:%S")
nextDay_t <- as.POSIXct(nextDay_t, format='%Y-%m-%d %H:%M:%S', tz="EST")

But still have only "2018-12-11 EST" instead of "2018-12-11 00:00:00 EST". Is there anything I'm missing in my code?

martinkabe
  • 1,079
  • 2
  • 12
  • 27
  • Possible duplicate of [Converting chr "00:00:00" to date-time "00:00:00"](https://stackoverflow.com/questions/25964504/converting-chr-000000-to-date-time-000000) – ismirsehregal Dec 10 '18 at 10:25
  • `nextDay_t` is a POSIXct object not a string, so is printed on the console as R thinks is prettier (in this specific case, removing hours when they are all zero). You just need to `format` that object when you want to print it – digEmAll Dec 10 '18 at 10:25
  • @digEmAll: yes, you are absolutely right! Thank you very much! – martinkabe Dec 10 '18 at 10:33

1 Answers1

2

Your code seems on the right track. The hour/minute/second components are in fact still there after calling strptime. They just do not show up automatically by default when inspecting the object.

You may try the following call to format, which includes these components, as well as the time zone (%Z):

nextDay_t <- strptime(paste0(as.character(Sys.Date() + 1)," 00:00:00"), format = "%Y-%m-%d %H:%M:%S")
nextDay_t
format(nextDay_t,"%Y/%m/%d %H:%M:%S %Z")  # include hour/minute/second and time zone

[1] "2018-12-11 CET"
[1] "2018/12/11 00:00:00 CET"
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Thank you Tim. This still doesn't work for me. As @digEmAll mentioned, R removes hours when they are all zero. – martinkabe Dec 10 '18 at 10:35
  • @martinkabe I think you're missing the point of that comment (and my answer). You should _not_ rely on R to print a POSIXct datetime the way you want. Instead, use the suggestion in my answer and the `format` function. `format` works in all cases AFAIK. – Tim Biegeleisen Dec 10 '18 at 10:41
  • 1
    @martinkabe: yep, Tim is right, the point of my comment is that the POSIXct object still has the hours information inside it but it just doesn't always print it on the console automatically... you need to `format` the object giving a specific format to be sure it prints as you desire – digEmAll Dec 10 '18 at 10:45
  • Yes, format keeps "%Y/%m/%d %H:%M:%S" but as character. It won't print the same after as.POSIXct formating which I need for further adding minutes/hours operations. – martinkabe Dec 10 '18 at 12:20