Convert Date to Numeric Time Object in R (Example) | hours, minutes & seconds Function

preview_player
Показать описание
R code:
x <- strptime("10:45:15", format = "%H:%M:%S") # Create date object
x # Print date object
# "2019-08-13 10:45:15 CEST"

library("lubridate") # Load lubridate package

hour(x) # Basic application of hour function
minute(x) # Basic application of minute function
second(x) # Basic application of second function

x_hours <- hour(x) + minute(x) / 60 + second(x) / 3600 # Convert date object to hours
x_hours # Print hours to RStudio console
# 10.75417

x_minutes <- hour(x) * 60 + minute(x) + second(x) / 60 # Convert date object to minutes
x_minutes # Print minutes to RStudio console
# 645.25

x_seconds <- hour(x) * 3600 + minute(x) * 60 + second(x) # Convert date object to seconds
x_seconds # Print seconds to RStudio console
# 38715
Рекомендации по теме
Комментарии
Автор

Can you convert a numeric object to HH:MM?

pipepi
Автор

Hi Sir,

I am trying to extract time from a date time variable but getting negative values, please help if possible.

Thanks in advance

shaikhzahid