EcoFlux
EcoFlux

Reputation: 35

Create a decimal hour column from a half-hourly datetime

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!

Upvotes: 1

Views: 135

Answers (2)

thelatemail
thelatemail

Reputation: 93813

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...

Upvotes: 1

hmhensen
hmhensen

Reputation: 3195

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.

Upvotes: 1

Related Questions