Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date time conversion and extract only time

Want to change the class for Time to POSIXlt and extract only the hours minutes and seconds

str(df3$Time) chr [1:2075259] "17:24:00" "17:25:00" "17:26:00" "17:27:00" ... 

Used the strptime function

df33$Time <- strptime(df3$Time, format = "%H:%M:%S")  

This gives the date/time appended

> str(df3$Time)  POSIXlt[1:2075259], format: "2015-08-07 17:24:00" "2015-08-07 17:25:00" "2015-08-07 17:26:00" ... 

Wanted to extract just the time without changing the POSIXlt class. using the strftime function

df3$Time <- strftime(df3$Time, format = "%H:%M:%S")  

but this converts the class back to "char" -

> class(df3$Time) [1] "character" 

How can I just extract the time with class set to POSIX or numeric...

like image 559
Antex Avatar asked Aug 07 '15 11:08

Antex


People also ask

How do I extract just the time from a date?

To extract time only from datetime with formula, you just need to do as follow: 1. Select a blank cell, and type this formula =TIME(HOUR(A1),MINUTE(A1), SECOND(A1)) (A1 is the first cell of the list you want to extract time from), press Enter button and drag the fill handle to fill range.

How do I convert date and time to just date in Excel?

The following formula will help you converting date/time format cell to date only in Excel. 1. Select a blank cell you will place the date value, then enter formula =MONTH(A2) & "/" & DAY(A2) & "/" & YEAR(A2) into the formula bar and press the Enter key.

How do I extract time from a date in Excel?

Get Time Value With Formula. If a cell contains a combined date and time, you can use the INT function to pull the time value into a separate column. Dates are stored as numbers in Excel, with the decimal portion representing the time.


1 Answers

If your data is

a <- "17:24:00"  b <- strptime(a, format = "%H:%M:%S") 

you can use lubridate in order to have a result of class integer

library(lubridate) hour(b) minute(b)  # > hour(b) # [1] 17 # > minute(b) # [1] 24   # > class(minute(b)) # [1] "integer" 

and you can combine them using

# character paste(hour(b),minute(b), sep=":")  # numeric hour(b) + minute(b)/60 

for instance.

I would not advise to do that if you want to do any further operations on your data. However, it might be convenient to do that if you want to plot the results.

like image 180
rmuc8 Avatar answered Oct 21 '22 18:10

rmuc8