【问题标题】:dateTime with different format in data frame数据框中具有不同格式的日期时间
【发布时间】:2013-12-19 08:23:34
【问题描述】:

我已经将一些数据导入到 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 列的类是因子,第二列是数字。

我尝试将 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

我认为这与 dateTime 以显示小时的格式变化有关,例如12、1、2 等,而不是 12、01、02。

如何将其更改为 POSIXct?

【问题讨论】:

    标签: r datetime


    【解决方案1】:

    你需要指定格式:

    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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 2018-12-27
      • 2014-02-03
      • 2013-09-01
      • 2020-03-30
      相关资源
      最近更新 更多