Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip the date and keep the time

Tags:

datetime

r

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.

like image 257
nacnudus Avatar asked Apr 13 '13 00:04

nacnudus


People also ask

How do you strip time from a date?

Step 1: Highlight the cells to remove time from date. Step 2: Then right-click on it and choose Format Cells… Step 3:-Then in the Format Cells box select Date in Category and select *14-03-2012 in Type, and then click Ok. After that time is removed from the date.


2 Answers

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."

like image 104
GSee Avatar answered Oct 04 '22 09:10

GSee


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
like image 43
Matthew Lundberg Avatar answered Oct 04 '22 07:10

Matthew Lundberg