Date time conversion and extract only time

You can also use the chron package to extract just times of the day:

library(chron) 

# current date/time in POSIXt format as an example
timenow <- Sys.time()

# create chron object "times"
onlytime <- times(strftime(timenow,"%H:%M:%S"))

> onlytime
[1] 14:18:00
> onlytime+1/24
[1] 15:18:00
> class(onlytime)
[1] "times"

If your data is

a <- "17:24:00"

b <- strptime(a, format = "%H:%M:%S")

you can use lubridate in order to have a result of class integer

library(lubridate)
hour(b)
minute(b)

# > hour(b)
# [1] 17
# > minute(b)
# [1] 24


# > class(minute(b))
# [1] "integer"

and you can combine them using

# character
paste(hour(b),minute(b), sep=":")

# numeric
hour(b) + minute(b)/60

for instance.

I would not advise to do that if you want to do any further operations on your data. However, it might be convenient to do that if you want to plot the results.


A "modern" tidyverse answer to this is to use hms::as_hms()

For example

library(tidyverse)
library(hms)

as_hms(1)
#> 00:00:01
as_hms("12:34:56")
#> 12:34:56

or, with your example data:

x <- as.POSIXlt(c("17:24:00", "17:25:00", "17:26:00", "17:27:00"), format = "%H:%M:%S")

x
#>[1] "2021-04-10 17:24:00 EDT" "2021-04-10 17:25:00 EDT" "2021-04-10 17:26:00 EDT" "2021-04-10 17:27:00 EDT"

as_hms(x)
# 17:24:00
# 17:25:00
# 17:26:00
# 17:27:00

See also docs here: https://hms.tidyverse.org/reference/hms.html


A datetime object contains date and time; you cannot extract 'just time'. So you have to think throught what you want:

  • POSIXlt is a Datetime representation (as a list of components)
  • POSIXct is a different Datetime representation (as a compact numeric)

Neither one omits the Date part. Once you have a valid object, you can choose to display only the time. But you cannot make the Date part disappear from the representation.