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

通过strftime()对字符执行POSIXct将产生错误的结果,r,datetime,strftime,posixct,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("P

我在使用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()的行为与我过去的经历不同。感谢您的帮助

您必须在通话中将时区明确设置为
strtime
。未使用
POSIXct
对象的
tzone
属性

strftime(df1$FlowDate3, format="%Y-%m-%d", tz=attr(df1$FlowDate3, "tzone"))

这种情况一直都是这样,还是最近R发行版的新要求?我不记得曾经这样做过……时区总是令人困惑。@stokeinfo:您以前可能不必这样做,因为您的数据没有
tzone
属性,或者它存在,但设置为您的本地时区。我不知道它最近是否在R中发生了变化。你需要查看新闻文件和/或svn历史记录。明白了。时区对我的数据并不重要,因此如何确保我的数据没有时区属性?B/c,当我在没有指定时区的情况下使用as.POSIXct()格式化时,它会抛出4条警告,表示没有指定时区它会感到不愉快。@stokeinfo:Use
attr(x,'tzone'))