R - 使用HHMMSS格式将日期和时间字段转换为POSIXct

时间:2013-04-30 13:32:16

标签: r datetime posixct

我有一个数据文件,因此有三列:

20010101 000000  0.833
20010101 000500  0.814
20010101 001000  0.794
20010101 001500  0.772
...

人眼相当清楚,前两个是日期和时间。我需要将它们转换为POSIXct(如果它更好的话,还是其他的东西,但我在R中处理时间戳的有限经验是使用POSIXct)。通常情况下,使用read.table将其拉入,我会使用:

df$DateTime <- as.POSIXct(paste(df$Date, df$Time), format="%Y%m%d %H%M%S")

然而,第二列似乎失去了它的前导零(可能是通过类型强制?),因此它无法正常工作。

我查看了Combine date as integer and time as factor to POSIXct in RConverting two columns of date and time data to one,但两者都使用了分隔符,例如:,因此没有相同的问题。

如何将这些列转换为POSIXct?

3 个答案:

答案 0 :(得分:16)

你非常接近。以下“简单”强制将前两列作为字符串读取,从而保存前导零。

R> df <- read.table(text="20010101 000000  0.833
20010101 000500  0.814
20010101 001000  0.794
20010101 001500  0.772", 
+ header=FALSE, colClasses=c("character", "character", "numeric"), 
+ col.names=c("Date", "Time", "Val"))
R> df
      Date   Time   Val
1 20010101 000000 0.833
2 20010101 000500 0.814
3 20010101 001000 0.794
4 20010101 001500 0.772

现在你正在尝试“正常工作”:

R> df$DateTime <- as.POSIXct(paste(df$Date, df$Time), format="%Y%m%d %H%M%S")
R> df
      Date   Time   Val            DateTime
1 20010101 000000 0.833 2001-01-01 00:00:00
2 20010101 000500 0.814 2001-01-01 00:05:00
3 20010101 001000 0.794 2001-01-01 00:10:00
4 20010101 001500 0.772 2001-01-01 00:15:00
R> 

答案 1 :(得分:3)

您只需将数据导入为字符:

txt <- "Date  Time  value
20010101 000000  0.833
20010101 000500  0.814
20010101 001000  0.794
20010101 001500  0.772
"

df <- read.table(text=txt, header=TRUE, 
                 colClasses=c("character", "character", "numeric"))

df$DateTime <- as.POSIXct(paste(df$Date, df$Time), format="%Y%m%d %H%M%S")

答案 2 :(得分:1)

简单地说,您可以使用非常棒且快速的lubridate包。为了您的目的尝试这个:

{ 'nameInDirective': '=nameOnParent' }

只需要输入正确的格式即可。我更喜欢它df <- read.table(text="20010101 000000 0.833 20010101 000500 0.814 20010101 001000 0.794 20010101 001500 0.772", header=FALSE, colClasses=c("character", "character", "numeric"), col.names=c("Date", "Time", "Val")) df$mix <- paste(df$Date, df$Time) df$mix <- parse_date_time(df$mix, 'Ymd HMS') ,因为它更灵活,你有其他功能来处理时间变量。

相关问题