Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert hours as a float to a 12h timestamp in R

I have a dataframe that contains values such as 8.6, 9.32, 9.79, etc. These values represent hours and fractions of hours. For instance, 8.6 hours equates to 08:36am, and 9.79 hours equates to 09:47am. I’m looking for an easy way to convert these floats into a timestamp. One approach could be to parse the fractional portion of the float and multiply by 60 to get the number of minutes, then convert to a timestamp. However, I’m wondering if anyone has a better solution using something like lubridate to convert the float to a timestamp.

df <- structure(list(start_time = c(8.6, 9.32, 9.79, 10.09, 10.63, 
8.64)), row.names = c(NA, 6L), class = "data.frame")

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df$start_time_hms = hms::as_hms(df$start_time*60*60)

  start_time  start_time_hms
1       8.60 08:36:00.000000
2       9.32 09:19:12.000000
3       9.79 09:47:24.000000
4      10.09 10:05:24.000000
5      10.63 10:37:48.000000
6       8.64 08:38:24.000000

Or if you want a POSIXct datetime:

df$start_time_hms = lubridate::ymd_hms("2022-06-24 00:00:00") + df$start_time*60*60


  start_time      start_time_hms
1       8.60 2022-06-24 08:36:00
2       9.32 2022-06-24 09:19:12
3       9.79 2022-06-24 09:47:24
4      10.09 2022-06-24 10:05:24
5      10.63 2022-06-24 10:37:48
6       8.64 2022-06-24 08:38:24
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading