Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want only the time portion of a date-time object in R

Tags:

time

r

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

like image 413
Erroldactyl Avatar asked Oct 18 '13 23:10

Erroldactyl


People also ask

How do I get only the date from a timestamp in R?

Method 1: Date is extracted from timestamp (column: Logout_time) using Format() function as shown below. So the resultant data frame has a column date_component with date extracted from timestamp. So the resultant data frame has a column date_component with date extracted from timestamp.

How do I separate days from date in R?

You can simply use weekdays(df$date) to extract the day of the week from the date. Only make sure the column is of type Date or convert using as. Date() .

What is POSIXct and POSIXlt?

There are two POSIX date/time classes, which differ in the way that the values are stored internally. The POSIXct class stores date/time values as the number of seconds since January 1, 1970, while the POSIXlt class stores them as a list with elements for second, minute, hour, day, month, and year, among others.


1 Answers

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.

like image 76
IRTFM Avatar answered Nov 15 '22 19:11

IRTFM