I have a vector of times in R, all_symbols$Time and I am trying to find out how to get JUST the times (or convert the times to strings without losing information). I use
strptime(all_symbol$Time[j], format="%H:%M:%S")
which for some reason assumes the date is today and returns
[1] "2013-10-18 09:34:16"
Date and time formatting in R is quite annoying. I am trying to get the time only without adding too many packages (really any--I am on a school computer where I cannot install libraries).
Once you use
strptime
you will of necessity get a date-time object and the default behavior for no date in the format string is to assume today's date. If you don't like that you will need to prepend a string that is the date of your choice.@James' suggestion is equivalent to what I was going to suggest:
The only package I know of that has time classes (i.e time of day with no associated date value) is package:chron. However I find that using format as a way to output character values from POSIXt objects lends itself well to functions that require factor input.
Came across the same problem recently and found this and other posts R: How to handle times without dates? inspiring. I'd like to contribute a little for whoever has similar questions.
If you only want to you base R, take advantage of
as.Date(..., format = ("..."))
to transform your date into a standard format. Then, you can usesubstr
to extract the time. e.g.substr("2013-10-01 01:23:45 UTC", 12, 16)
gives you01:23
.If you can use package
lubridate
, functions likemdy_hms
will make life much easier. Andsubstr
works most of the time.If you want to compare the time, it should work if they are in Date or POSIXt objects. If you only want the time part, maybe force it into numeric (you may need to transform it back later). e.g.
as.numeric(hm("00:01"))
gives60
, which means it's 60 seconds after 00:00:00.as.numeric(hm("23:59"))
will give86340
.