首页 文章

dateTime在数据框中具有不同的格式

提问于
浏览
1

我已将一些数据导入R,如下所示:

dateTime  temp
1 10/25/2005 12:00:00  15.50
2  10/25/2005 1:00:00  15.49
3  10/25/2005 2:00:00  15.52
4  10/25/2005 3:00:00  15.50
5  10/25/2005 4:00:00  15.50
6  10/25/2005 5:00:00  15.46

其中data.frame的dateTime列的类是factor,第二列是numeric .

我尝试将dateTime转换为POSIXct格式,如下所示:

dat[,1] <- as.POSIXct(dat[,1])

但收到错误

Error in as.POSIXlt.character(as.character(x), ...) : 
  character string is not in a standard unambiguous format

我认为这与日期时间有关,该时间以小时的格式变化,例如12,1,2等,而不是12,01,02 .

如何将其更改为POSIXct?

1 回答

  • 2

    您需要指定格式:

    datetime <- factor("10/25/2005 12:00:00")
    
    as.POSIXct(datetime)
    #Error in as.POSIXlt.character(as.character(x), ...) : 
    #  character string is not in a standard unambiguous format
    
    as.POSIXct(datetime, format="%m/%d/%Y %H:%M:%S")
    #[1] "2005-10-25 12:00:00 CEST"
    

    注意:我建议您在创建日期时间变量时始终明确指定时区 . 否则,您可能会遇到夏令时问题 .

    as.POSIXct(datetime, format="%m/%d/%Y %H:%M:%S", tz="GMT")
    #[1] "2005-10-25 12:00:00 GMT"
    

相关问题