r - 通过 strftime() 将 POSIXct 转换为字符会产生错误的结果

标签 r datetime strftime posixct

我在使用 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/

相关文章:

regex - 将正则表达式与文字字符串结合

r - 无法从 OpenSUSE Leap 15.2 安装 arm 和 lme4 软件包

python库从给定字符串中提取日期格式

c++ - 如何在 Linux 和 Windows 上获取时间戳字符串

iphone - 使用 strftime 将 NSDate 转换为字符串

r - 在 R 中,如何定义模型对比来比较相对于公共(public)控件的两个条件?

r - 哪个有什么用?

php - 数据库中的日期时间值晚了三个小时

datetime - 将 64 位时间戳转换为可读值

c - 在 C 中比较没有日期的时间(小时和秒)的最佳方法?