3

I have data in the form of minutes after midnight. For example, "70" corresponds to 1:10am. I am trying to convert it to HH:mm in R so that I can do some time series analyses.

Here is the code I have tried:

xtime <- as.numeric(as.character(occur_dat$Minutes_After_12am))


x_time <- format(as.POSIXct(xtime, origin = "00:00"), format = "%H:%M")

I verified that xtime is a numeric vector, and it is. I am not sure why I keep getting the "character string is not in a standard unambiguous format" error. Similar questions appear to be resolved with the first line of code (as.numeric), so I am at a loss.

jay.sf
  • 60,139
  • 8
  • 53
  • 110
Joann
  • 33
  • 3
  • `origin=` has to be a date-time, not just time. You should type `?as.POSIXct` and read the documentation. – jay.sf Mar 24 '23 at 06:51

3 Answers3

2

Use a period/time class from a package. I like package data.table but I think lubridate and chron also provide such classes.

library(data.table)

#75 minutes after midnight
x <- as.ITime(75 * 60)
#"01:15:00"
sprintf("%02d:%02d", hour(x), minute(x))
#[1] "01:15"
Roland
  • 127,288
  • 10
  • 191
  • 288
1

The orgin "00:00" does not support in as.POSIXct. You may debug by changing the parameters one by one in functions to check where go wrong. Please check below code in order to get your outcome.

xtime <- 70

time_lt <- format(as.POSIXlt(xtime * 60, origin = "1970-01-01", tz = "UTC"),format = "%H:%M")

print(time_lt)
limlim1
  • 86
  • 2
0

You were close. origin= has to be in date-time format (not necessarily class) such as "2023-03-24 08:53:30". Using just a date "2023-03-24" defaults to midnight. Since the date in this case is arbitrary we also could use Sys.Date().

Because x in as.POSIXct can be specified as "the number of seconds since [the origin]", you need to multiply the minutes by 60. To format we can use strftime.

xtime <- c(0, 30, 60, 90)

strftime(as.POSIXct(xtime*60, origin=Sys.Date()), format="%H:%M", tz='GMT')
# [1] "00:00" "00:30" "01:00" "01:30"

Also read ?as.POSIXct.

jay.sf
  • 60,139
  • 8
  • 53
  • 110
  • 1
    Thank you, I found some examples that specified the format as %H:%M%S that were able to avoid using that date, and was trying to modify that, but I see that does not work! Thank you! – Joann Mar 24 '23 at 13:29