我在使用 strftime() 从 POSIXct 日期时间对象中提取正确的字符值时遇到问题。我的示例数据的 dput() 如下:
dput(df1)
structure(list(FlowDate3 = structure(c(1388534400, 1388534400,
1388534400, 1388534400, 1388534400, 1388534400, 1388534400, 1388534400,
1388534400, 1388534400), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
FlowDate4 = c("2013-12-31", "2013-12-31", "2013-12-31", "2013-12-31",
"2013-12-31", "2013-12-31", "2013-12-31", "2013-12-31", "2013-12-31",
"2013-12-31")), .Names = c("FlowDate3", "FlowDate4"), row.names = c(NA,
10L), class = "data.frame")
看起来像这样:
> df1
FlowDate3 FlowDate4
1 2014-01-01 2013-12-31
2 2014-01-01 2013-12-31
3 2014-01-01 2013-12-31
4 2014-01-01 2013-12-31
5 2014-01-01 2013-12-31
6 2014-01-01 2013-12-31
7 2014-01-01 2013-12-31
8 2014-01-01 2013-12-31
9 2014-01-01 2013-12-31
10 2014-01-01 2013-12-31
> str(df1)
'data.frame': 10 obs. of 2 variables:
$ FlowDate3: POSIXct, format: "2014-01-01" "2014-01-01" "2014-01-01" ...
$ FlowDate4: chr "2013-12-31" "2013-12-31" "2013-12-31" "2013-12-31" ...
要创建 FlowDate4,我执行了以下操作:
> strftime(df1$FlowDate3, "%Y-%m-%d")
[1] "2013-12-31" "2013-12-31" "2013-12-31" "2013-12-31" "2013-12-31" "2013-12-31"
[7] "2013-12-31" "2013-12-31" "2013-12-31" "2013-12-31"
正如您所看到的,FlowDate3 中的日期产生了错误的字符串……年、月和日期都关闭了。我跑了无数圈试图找出原因,但完全不知所措。 strftime() 的行为不像我过去所经历的那样。任何帮助表示赞赏。
最佳答案
您必须在调用中明确设置时区 strptime
. tzone
您的 POSIXct
的属性不使用对象。
strftime(df1$FlowDate3, format="%Y-%m-%d", tz=attr(df1$FlowDate3, "tzone"))
关于r - 通过 strftime() 将 POSIXct 转换为字符会产生错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27384724/