1

I would like to create a new column containing a decimal hour using a half-hourly datetime column which is in POSIXct format.

Essentially my datetime column is like this: "2015-09-01 09:00:00, 2015-09-01 09:30:00, 2015-09-01 10:00:00" etc...

I would like the new decimal hour column to look like this: "9, 9.5, 10" etc...

Thank you!

EcoFlux
  • 35
  • 4

2 Answers2

1

I used one of your times as an example.

time <- as.POSIXct("2015-09-01 09:30:00", tz = "GMT")
(as.numeric(time) %% 86400) / 3600
[1] 9.5

The code provides the desired output.

For why, see Matthew Lundberg's answer by following the link: Extracting time from POSIXct.

hmhensen
  • 2,974
  • 3
  • 22
  • 43
1

difftime is a great little function, which if you combine with trunc here, will give you your answer:

x <- as.POSIXct(c("2015-09-01 09:00:00", "2015-09-01 09:30:00", "2015-09-01 10:00:00"))

difftime(x, trunc(x, units="days"), units="hours")
#Time differences in hours
#[1]  9.0  9.5 10.0

Obviously this is neat and easy to change if you want your output units= in "mins" "days" etc...

thelatemail
  • 91,185
  • 12
  • 128
  • 188