Jazzmine
Jazzmine

Reputation: 1875

R function to convert time of day to total minutes

I need to take the time of day (e.g. 13:34) and convert it to minute number or number of minutes in a day it represents so the expected answer would be (780 + 34) or 814 minutes

I was thinking about extracting the hours and minutes into variables probably using lubridate and of course, multiplying the hours by 60 and adding the minutes.

But is there a method or function that I can use for this that already exists? Thought I'd check with the SO community.

Thanks

Upvotes: 4

Views: 3180

Answers (1)

Jazzmine
Jazzmine

Reputation: 1875

Thanks to rawr - providing a POSIX type answer that worked just fine:

difftime(as.POSIXct('13:34', format = '%H:%M'), as.POSIXct('00:00', format = '%H:%M'), units = 'min')

For everyone here's the output I got:

z<-difftime(as.POSIXct('13:34', format = '%H:%M'), as.POSIXct('00:00', format = '%H:%M'), units = 'min') 

#print out z
> z 

#response
Time difference of 814 mins 

#confirm that z only has the 814 as value
> typeof(z) [1] "double"

Upvotes: 4

Related Questions