如何转换时间R的格式? [英] How to convert format of time R?
问题描述
我有一个具有以下格式的时间的数据框:
I have a dataframe with the time in the following format:
Time
01.01.2017 01:00
01.01.2017 02:00
01.01.2017 03:00
01.01.2017 04:00
01.01.2017 05:00
01.01.2017 06:00
class(df$Time)
[1] "factor"
它的天,月,年,小时,分钟。我想将其转换为可读时间。我已经尝试过了:
Its day, month, year, hours, minutes. I want to convert it into a readable time. I tried this already:
strptime(df$Time, format="%d-%m-%Y %H:%M")
as.POSIXct(df$Time)
它不起作用。如何将其转换并将格式更改为:2017-01-01 01:00。所以我想要年,月,日,小时,分钟。
It doesnt work. How can I transform it and change the format to: 2017-01-01 01:00. So I want to have Year, month, day, hours, minutes.
推荐答案
阅读?strptime
,您需要格式
为
strptime("01.01.2017 01:00", format="%d.%m.%Y %H:%M")
#[1] "2017-01-01 01:00:00"
如果您需要使用特定格式的输出,我们可以使用 format
If you need output to be in the particular format we can use format
format(strptime("01.01.2017 01:00", format="%d.%m.%Y %H:%M"), "%Y-%m-%d %H:%M")
#[1] "2017-01-01 01:00"
相同将与 as.POSIXct
as.POSIXct("01.01.2017 01:00", format="%d.%m.%Y %H:%M")
或者直接忽略指定格式,请使用 lubridate :: dmy_hm
Or to ignore specifying formats directly use lubridate::dmy_hm
lubridate::dmy_hm("01.01.2017 01:00")
@ 42-提到的一件事要注意的是,尽管它们看起来相同,但 format
的输出是一个字符值,而 a的输出是一个字符值。 s.POSIXct
和 strptime
是日期时间值。
One thing to note as mentioned by @42- is although they look the same the output of format
is a character value whereas that of as.POSIXct
and strptime
is a datetime value.
这篇关于如何转换时间R的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!