Reputation: 2417
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")
Upvotes: 0
Views: 88
Reputation: 66415
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
Upvotes: 2