19

Lots of people ask how to strip the time and keep the date, but what about the other way around? Given:

myDateTime <- "11/02/2014 14:22:45"

I would like to see:

myTime
[1] "14:22:45"

Time zone not necessary.

I've already tried (from other answers)

as.POSIXct(substr(myDateTime, 12,19),format="%H:%M:%S")

[1] "2013-04-13 14:22:45 NZST"

The purpose is to analyse events recorded over several days by time of day only.

Thanks

Edit:

It turns out there's no pure "time" object, so every time must also have a date.

In the end I used

as.POSIXct(as.numeric(as.POSIXct(myDateTime)) %% 86400, origin = "2000-01-01")

rather than the character solution, because I need to do arithmetic on the results. This solution is similar to my original one, except that the date can be controlled consistently - "2000-01-01" in this case, whereas my attempt just used the current date at runtime.

nacnudus
  • 6,328
  • 5
  • 33
  • 47
  • 2
    I eventually stumbled upon chron, which has an object of class "times". This makes addition much easier, e.g. 18:00 + 12:00 = 1.25 days. – nacnudus May 27 '13 at 00:00
  • 2
    you can also use the `hms` package after calling `format()`, i.e. `hms::as.hms(x)` – Von Jun 20 '17 at 20:25

2 Answers2

28

I think you're looking for the format function.

(x <- strptime(myDateTime, format="%d/%m/%Y %H:%M:%S"))
#[1] "2014-02-11 14:22:45"
format(x, "%H:%M:%S")
#[1] "14:22:45"

That's character, not "time", but would work with something like aggregate if that's what you mean by "analyse events recorded over several days by time of day only."

GSee
  • 48,880
  • 13
  • 125
  • 145
  • I am facing an issue in strptime function. If I add a text just before the date like this: strptime("hello Tue, 23 Mar 2010 14:36:38 -0400", "%a, %d %b %Y %H:%M:%S %z") #NA Any idea where is the issue – Ankit Jun 07 '13 at 14:14
  • @Ankit you have to account for it in the `format` argument. Try this: `strptime("hello Tue, 23 Mar 2010 14:36:38 -0400", "hello %a, %d %b %Y %H:%M:%S %z")` – GSee Jun 07 '13 at 16:05
  • @GSee Great answer. This is what I was looking for. – dataanalyst Sep 01 '16 at 20:05
4

If the time within a GMT day is useful for your problem, you can get this with %%, the remainder operator, taking the remainder modulo 86400 (the number of seconds in a day).

stamps <- c("2013-04-12 19:00:00", "2010-04-01 19:00:01", "2018-06-18 19:00:02")
as.numeric(as.POSIXct(stamps)) %% 86400
## [1] 0 1 2
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112