通过strftime()对字符进行POSIXct会产生错误的结果

时间:2014-12-09 17:09:50

标签: r datetime strftime posixct

我在使用strftime()从POSIXct datetime对象中提取正确的字符值时遇到问题。我的样本数据的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()的行为并不像我过去经历的那样。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

您必须在调用strptime时明确设置时区。 tzone属性未使用。

POSIXct