我在使用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调用中明确设置时区.未使用POSIXct对象的tzone属性.
strftime(df1$FlowDate3, format="%Y-%m-%d", tz=attr(df1$FlowDate3, "tzone"))