Extract clock time from datetime values in R

How to extract the time of day from a datetime in R with base R, lubridate and hms, and what each output keeps or loses for display, analysis and sharing.

In R, extracting the time from a datetime can produce three different things: a formatted string such as "14:30:45", separate numeric parts such as hour 14, or a time-of-day value that still supports sorting and arithmetic. The function you call matters less than which of these outputs you need. This review explains what each approach changes, where it fits, and what survives when the result is copied, exported or shared.

Is this transformation suitable for your intended use?

For display, labels and reports, use base R format() with an explicit format string. It is readable, has no dependencies, and copies as plain text. For grouping or filtering by hour, use lubridate's hour(), minute() and second(), which return numbers. For a time-of-day column you will sort, subtract or summarise, use hms::as_hms(), which keeps the value numeric (seconds since midnight) while printing as HH:MM:SS.

The main tradeoff is between a character string and a time value. A string is the most portable and human-readable result. It cannot be used in arithmetic, though, and R will not catch an invalid entry such as "25:61". Plain text is preferable when the extracted time is a final output, such as a report column, a chart label or a file for people who do not use R. Keep a time value while analysis is still in progress. In every case, keep the original datetime column. Once the date and time zone are dropped, they cannot be recovered from the clock time alone.

What extraction actually changes

Despite falling under text transformation, this operation does not reverse, mirror or restyle characters. Nothing is reordered, no glyphs are substituted, and no bidirectional display is involved. A POSIXct value stores a number of seconds since 1970-01-01 00:00:00 UTC, plus a time zone attribute that controls how that instant is printed. Extraction creates a new value that drops the date. The original column stays unchanged unless you overwrite it.

It is important to separate stored values from how they are presented. Changing the time zone used for display, for example with format(..., tz =) or lubridate::with_tz(), changes the clock time you see but not the underlying instant. lubridate::force_tz() does the opposite: it keeps the printed clock time and changes the stored instant. Which of these you apply before extraction determines the time you get.

x <- as.POSIXct("2024-03-15 14:30:45", tz = "UTC")

format(x, "%H:%M:%S")                         # "14:30:45"
format(x, "%H:%M", tz = "America/New_York")  # "10:30"
lubridate::hour(x)                            # 14
hms::as_hms(x)                                # 14:30:45

The New York result is four hours earlier, not five, because US daylight saving time began on March 10, 2024. The same code run on a January date would show a five-hour difference. This is the most common reason an extracted time looks wrong.

Base R: format(), strftime() and POSIXlt

format(x, "%H:%M:%S")      # 24-hour string
format(x, "%I:%M %p")      # 12-hour string, e.g. "02:30 PM"
strftime(x, "%H:%M:%S")    # equivalent string output

lt <- as.POSIXlt(x)
lt$hour                    # 14 (0-23)
lt$min                     # 30
lt$sec                     # 45 (can be fractional)

format() and strftime() return character vectors. Converting to POSIXlt gives you the parts as numbers without loading any packages. Both approaches use the object's time zone attribute unless you pass a tz argument.

lubridate: hour(), minute() and second()

library(lubridate)

hour(x)     # 14
minute(x)   # 30
second(x)   # 45

# hour of day in another zone, without changing the instant
hour(with_tz(x, "America/New_York"))  # 10

These functions return numbers, which suits grouping, filtering and binning, for example counting events per hour. Note the naming overlap. lubridate::hms() parses a string such as "14:30:45" into a Period object, while hms::hms() and hms::as_hms() create a time-of-day class. They are different types with different behaviour. If both packages are loaded, call them with the package prefix.

hms: a time-of-day value you can still compute with

library(hms)

t <- as_hms(x)          # 14:30:45
as.numeric(t)           # 52245 seconds since midnight
t - as_hms("09:00:00")  # difference as a time span

hms values print like clock times but are stored as seconds, so they sort correctly and support arithmetic. To get the clock time for a specific zone, convert the datetime with with_tz() first. Then check one known value to confirm the output matches what you expect.

Starting from a timestamp stored as text or a number

# text: base R uses the session's local zone unless tz is given
p1 <- as.POSIXct("2024-03-15 14:30:45", tz = "UTC")

# text: lubridate parsers default to UTC
p2 <- lubridate::ymd_hms("2024-03-15 14:30:45")

# Unix timestamp in seconds
p3 <- as.POSIXct(1710513045, origin = "1970-01-01", tz = "UTC")

format(p3, "%H:%M:%S")  # "14:30:45"

Parse text and numeric timestamps into a datetime before extracting the time. The default time zones differ: as.POSIXct() without tz uses the local zone of the machine running the code, while ymd_hms() uses UTC. The same script can therefore return different results on different computers. Set tz explicitly. Timestamps in milliseconds must be divided by 1000 first. A Date object has no time component, so extracting from it always gives midnight.

Will the result remain readable and usable after copying or sharing?

Output | R type | Sorts correctly | Arithmetic | When shared outside R
format(x, "%H:%M:%S") | character | Yes, if 24-hour and zero-padded | No | Plain text; copies exactly
format(x, "%I:%M %p") | character | No | No | Readable; AM/PM label depends on locale
hour(), minute(), second() | numeric | Yes | Yes | Numbers without context; label the columns
hms::as_hms(x) | hms (seconds) | Yes | Yes | Prints as HH:MM:SS; check how your export writes it

Because extraction does not reorder or substitute characters, reading order, search and editing work as they would for any ordinary text. A string like "14:30" is plain ASCII. Some risks remain. A 12-hour time without AM or PM is ambiguous. The text produced by %p can vary with the system locale. Spreadsheet applications and other import tools may reinterpret time-like text as their own time type. No destination-specific test was supplied for this review, so read the exported file back, or open it in the target application, before relying on it. Likewise, no assistive-technology testing was available. Writing out a 24-hour time, or including AM or PM, is the least ambiguous option for any reader.

A plain-text version is needed whenever recipients do not use R, or when the time zone is not obvious from context. In those cases, include the zone in the string, for example with format(x, "%H:%M %Z"), or state it in the column name.

Pitfalls worth checking

  • %M is minutes and %m is month; swapping them gives plausible but wrong output.
  • Printing a POSIXct vector where every value is at midnight hides the time; an explicit format string shows 00:00:00.
  • Around daylight saving changes, some clock times occur twice and some do not occur at all, so two different instants can produce the same extracted time.
  • Fractional seconds are hidden by default; use "%H:%M:%OS3" for milliseconds, and note that floating-point storage can make the last digit display one unit lower.
  • Converting with force_tz() when you meant with_tz() shifts the stored instant and gives a different clock time.

Gaps in this review

No benchmarks, version-specific test results or destination-specific export tests were supplied, so this review does not compare speed and makes no claims about any particular spreadsheet, database or screen reader. The behaviour described follows the documented conventions of base R, lubridate and hms. Defaults can change between versions, so confirm against the versions you have installed by checking one known timestamp.