Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...