日期时间转换并仅提取时间 [英] Date time conversion and extract only time

查看:110
本文介绍了日期时间转换并仅提取时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想要将时间类更改为POSIXlt,并且仅提取小时分钟和秒

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

使用了strptime函数

Used the strptime function

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

这会附加日期/时间

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

希望仅提取时间而不更改POSIXlt类。使用strftime函数

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

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

但这会将类转换回 char-

but this converts the class back to "char" -

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

我如何提取类别设置为POSIX或数字的时间...

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

推荐答案

如果您的数据是

a <- "17:24:00"

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

您可以使用 lubridate 为了得到类 integer

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"

结合使用

# character
paste(hour(b),minute(b), sep=":")

# numeric
hour(b) + minute(b)/60


$ b例如$ b

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.

这篇关于日期时间转换并仅提取时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆