【问题标题】:Difference between as.POSIXct/as.POSIXlt and strptime for converting character vectors to POSIXct/POSIXltas.POSIXct/as.POSIXlt 和 strptime 之间的区别,用于将字符向量转换为 POSIXct/POSIXlt
【发布时间】:2012-05-28 19:05:14
【问题描述】:

我在这里关注了一些关于如何将字符向量转换为日期时间类的问题。我经常看到两种方法,strptime 和 as.POSIXct/as.POSIXlt 方法。我查看了这 2 个函数,但不清楚有什么区别。

strptime

function (x, format, tz = "") 
{
    y <- .Internal(strptime(as.character(x), format, tz))
    names(y$year) <- names(x)
    y
}
<bytecode: 0x045fcea8>
<environment: namespace:base>

as.POSIXct

function (x, tz = "", ...) 
UseMethod("as.POSIXct")
<bytecode: 0x069efeb8>
<environment: namespace:base>

as.POSIXlt

function (x, tz = "", ...) 
UseMethod("as.POSIXlt")
<bytecode: 0x03ac029c>
<environment: namespace:base>

做一个微基准测试看看是否存在性能差异:

library(microbenchmark)
Dates <- sample(c(dates = format(seq(ISOdate(2010,1,1), by='day', length=365), format='%d-%m-%Y')), 5000, replace = TRUE)
df <- microbenchmark(strptime(Dates, "%d-%m-%Y"), as.POSIXlt(Dates, format = "%d-%m-%Y"), times = 1000)

Unit: milliseconds
                                    expr      min       lq   median       uq      max
1 as.POSIXlt(Dates, format = "%d-%m-%Y") 32.38596 33.81324 34.78487 35.52183 61.80171
2            strptime(Dates, "%d-%m-%Y") 31.73224 33.22964 34.20407 34.88167 52.12422

strptime 似乎稍快一些。那么什么给了?为什么会有 2 个相似的功能,或者我错过了它们之间的差异?

【问题讨论】:

  • 如果您想查看在字符向量上调用as.POSIXctas.POSIXlt 时调用了什么代码,请分别查看as.POSIXct.defaultas.POSIXlt.character

标签: r date time benchmarking


【解决方案1】:

嗯,函数做不同的事情。

首先,日期/时间有两个内部实现:POSIXct,它存储自 UNIX 纪元以来的秒数(+一些其他数据),以及 POSIXlt,它存储日、月、年、小时的列表,分、秒等

strptime是直接将字符向量(多种格式)转换为POSIXlt格式的函数。

as.POSIXlt 将多种数据类型转换为POSIXlt。它试图变得聪明并做明智的事情——就角色而言,它充当strptime的包装器。

as.POSIXct 将多种数据类型转换为POSIXct。它还试图变得聪明,做明智的事情——在字符的情况下,它首先运行strptime,然后从POSIXlt转换为POSIXct

strptime 更快是有道理的,因为strptime 只处理字符输入,而其他人试图从输入类型中确定使用哪种方法。它也应该更安全一点,因为收到意外数据只会给出错误,而不是尝试做可能不是您想要的智能事情。

【讨论】:

  • 很好的答案。对于为建模或数据可视化目的编译数据的最佳做法是否存在共识?
【解决方案2】:

有两种 POSIXt 类型,POSIXct 和 POSIXlt。 “ct”可以代表日历时间,它存储了从起源开始的秒数。 “lt”或本地时间,将日期保存为时间属性列表(例如“小时”和“星期一”)。 试试这些例子:

date.hour=strptime("2011-03-27 01:30:00", "%Y-%m-%d %H:%M:%S")

date=c("26/10/2016")

time=c("19:51:30")

day<-paste(date,"T", time)

day.time1=as.POSIXct(day,format="%d/%m/%Y T %H:%M:%S",tz="Europe/Paris")

day.time1

day.time1$year

day.time2=as.POSIXlt(day,format="%d/%m/%Y T %H:%M:%S",tz="Europe/Paris")

day.time2

day.time2$year

【讨论】:

  • 太棒了! attributes() 也很有趣。也许你应该添加这个;-)
猜你喜欢
  • 2015-05-13
  • 1970-01-01
  • 2018-03-23
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多