Want only the time portion of a date-time object i

2019-02-06 07:32发布

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

标签: r time
2条回答
Emotional °昔
2楼-- · 2019-02-06 08:27

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:

format(all_symbol$Time[j], format="%H:%M:%S")

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.

查看更多
干净又极端
3楼-- · 2019-02-06 08:34

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 use substr to extract the time. e.g. substr("2013-10-01 01:23:45 UTC", 12, 16) gives you 01:23.

If you can use package lubridate, functions like mdy_hms will make life much easier. And substr 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")) gives 60, which means it's 60 seconds after 00:00:00. as.numeric(hm("23:59")) will give 86340.

查看更多
登录 后发表回答