【问题标题】:Date shows up as number日期显示为数字
【发布时间】:2013-01-24 08:36:17
【问题描述】:

我从 postgresql 获取了一组日期,它们看起来是正确的:

[1] "2007-07-13" "2007-07-14" "2007-07-22" "2007-07-23" "2007-07-24"
[6] "2007-07-25" "2007-08-13" "2007-08-14" "2007-08-15" "2007-08-16"
etc.

然后我想对它们运行一个循环来创建新的 sql 语句来获取其他一些数据集(是的,我知道我在做什么,不可能在数据库服务器中完成所有处理)

所以我尝试了

for(date in geilodates)
 mapdate(date,geilo)
Error in postgresqlExecStatement(conn, statement, ...) : 
  RS-DBI driver: (could not Retrieve the result : ERROR:  invalid input syntax for type date: "13707"
LINE 1: ...id_date_location where not cowid is null and date='13707' or...

mapdate是我写的一个函数,里面的日期使用是

sql=paste('select * from gps_coord where cowid=',cowid," and date='",date,"'",sep='')

所以,在我尝试将 sql 粘贴在一起之前,R 默默地将我的格式化日期转换为它们的整数表示。

如何获得日期的原始文本表示?我试过了

for(date in geilodates){
  d=as.Date(date,origin="1970-01-01")
  mapdate(d,geilo)
}
Error in charToDate(x) : 
character string is not in a standard unambiguous format

而且我还没有找到任何其他函数来创建日期字符串(或将日期“提供”为列出变量时得到的字符串

【问题讨论】:

标签: r postgresql date


【解决方案1】:

感谢 wush978 为我指明了正确的方向,最后我不得不这样做:

for(d in geilodates){
 date=format(as.Date(d,origin="1970-01-01"))
 mapdate(date,geilo)
}

由于某种原因,在循环中,“日期”变量被视为一个整数,所以我必须明确地将其转换为日期,然后对其进行格式化......

【讨论】:

  • “...出于某种原因”是因为 is.vector(Sys.Date()) 是 FALSE。 help('for') 说:“seq:计算向量的表达式...或对列表或'NULL'”,所以发生的事情(基本上)是as.vector(Sys.Date()) # 15729。
  • 谢谢,@JoshuaUlrich!这清楚了。 (希望我记得,直到下一次我需要它;-))
【解决方案2】:

试试?format.Date

x <- Sys.Date()
class(x)
class(format(x))

在 R 中,Date 类的数据是数值类型。 将Date 表示为字符串的官方方法是调用format。

我怀疑date 的格式是在你的情况下定义的,所以paste 做了一些意想不到的事情。

也许您需要将 format(x, "%Y-%m-%d") 放入您的 paste 函数而不是 date 以告诉 R 您希望使用哪种格式的日期。

【讨论】:

  • 谢谢,看起来像我需要的,但这很奇怪,我可以这样做: date=geilodates[1] > date [1] "2007-07-13" > class(date) [1 ] "Date" > d=format.Date(date,origin="1970-01-01") > d [1] "2007-07-13" > class(d) [1] "character" 看起来不错,但如果我把它放入 for 循环: for(date in geilodates){ + d=format.Date(date,origin="1970-01-01") + } 错误 in as.POSIXlt.numeric(x) :必须提供“原点”
  • @MortenSickel,也许您需要跟踪涉及变量的类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-03
相关资源
最近更新 更多