对于输出,规范为%Z(请参阅?strptime)。但是对于输入,这是如何工作的呢?

要澄清的是,最好通过as.POSIXct()将时区缩写解析为有用的信息,但更多的核心问题是如何使函数至少忽略时区。

这是我最好的解决方法,但是是否有要传递给as.POSIXct()的适用于所有时区的特定格式代码?

times <- c("Fri Jul 03 00:15:00 EDT 2015", "Fri Jul 03 00:15:00 GMT 2015")
as.POSIXct(times, format="%a %b %d %H:%M:%S %Z %Y") # nope! strptime can't handle %Z in input

formats <- paste("%a %b %d %H:%M:%S", gsub(".+ ([A-Z]{3}) [0-9]{4}$", "\\1", times),"%Y")
as.POSIXct(times, format=formats) # works

编辑:这是最后一行的输出以及它的类(来自单独的调用);输出是预期的。从控制台:
> as.POSIXct(times, format=formats)
[1] "2015-07-03 00:15:00 EDT" "2015-07-03 00:15:00 EDT"

> attributes(as.POSIXct(times, format=formats))
$class
[1] "POSIXct" "POSIXt"

$tzone
[1] ""

最佳答案

简短的回答是:“不,你不能。”这些是缩写,不能保证它们唯一地标识特定的时区。

例如,“EST”是美国或澳大利亚的东部标准时间吗?是美国或澳大利亚的“CST”中部标准时间,还是中国的标准时间,还是古巴的标准时间?

我只是注意到您没有尝试解析时区缩写,只是在试图避免它。我不知道一种告诉strptime忽略任意字符的方法。我确实知道它将忽略格式字符串结束后的时间的字符表示形式中的任何内容。例如:

R> # The year is not parsed, so the current year is used
R> as.POSIXct(times, format="%a %b %d %H:%M:%S")
[1] "2015-07-03 00:15:00 UTC" "2015-07-03 00:15:00 UTC"

除此之外,我只能想到一个正则表达式可以解决此问题。与您的示例不同,我将在输入字符向量上使用正则表达式来删除所有3-5个字符的时区缩写。
R> times_no_tz <- gsub(" [[:upper:]]{3,5} ", " ", times)
R> as.POSIXct(times_no_tz, format="%a %b %d %H:%M:%S %Y")
[1] "2015-07-03 00:15:00 UTC" "2015-07-03 00:15:00 UTC"

09-26 22:49
查看更多