【问题标题】:SQL casting seconds in time stamp to an integerSQL将时间戳中的秒数转换为整数
【发布时间】:2021-07-11 14:06:13
【问题描述】:

我正在尝试将数据集中时间戳变量中的秒数转换为整数。到目前为止,我已经将其归结为仅输出时间戳的秒数的子字符串,但无论出于何种原因,无论我在尝试时引用什么索引,我都无法摆脱最后的字母“Z”子字符串,以便我可以将值转换为整数。我已经包含了我的数据的屏幕截图以及我尝试对下面的值进行子串化。

这是我目前的输出,有人可以帮忙吗?

【问题讨论】:

  • 用文字代替截图
  • 这是我的代码文本:sqldf("select substring(time, 17, LENGTH(time)-1) from mydata limit 10;")
  • scto,请 (1) 不要发布代码或数据的图像,它假定我们将有时间和精力将您已经在 R 控制台中以文本形式保存的数据,在 R-友好的数据格式,见meta.stackoverflow.com/a/285557(和xkcd.com/2116); (2) cmets 很容易被读者遗漏或被 Stack 界面隐藏(当很多时)。如果您对问题有什么要补充的,那么edit 它并保持问题本身是独立的,没有 cmets。谢谢。

标签: sql r casting timestamp


【解决方案1】:

假数据

mydata <- data.frame(time = "2018-09-07T01:07:14.599Z")

编辑:我没有注意到substringsubstr 的别名,我已经更改了此处的文字以反映这一点。

substr 和别名substring 都将返回字符串的长度 作为最后一个参数。来自docs

substr(X,Y,Z) 函数返回输入字符串 X 的子字符串,该子字符串以第 Y 个字符开头,长度为 Z 个字符。 ...

这与使用startend 的一些(非sqlite)类似子字符串的实现形成对比,您的代码适用于这些实现。

sqldf::sqldf("select substr(time, 18, length(time)-18) from mydata")
#   substr(time, 18, length(time)-18)
# 1                            14.599

不过,我不知道您为什么要在其中引入 sqldf:虽然它很好,但在 R 中通过几种不同的方法执行此操作几乎肯定会快得多:

### notice that this is start,end not start,length
substr(mydata$time, 18, nchar(mydata$time)-1)
# [1] "14.599"

format(as.POSIXct(mydata$time, format="%Y-%m-%dT%H:%M:%OSZ"), format = "%OS3")
# [1] "14.598"             # the 598-vs-599 thing is due to floating-point IEEE-754

as.POSIXlt(mydata$time, format="%Y-%m-%dT%H:%M:%OSZ")$sec
# [1] 14.599               # numeric, not string

【讨论】:

  • SQLite 自 SQLite 版本 3.34.0 起支持 substring 作为 substr 的别名。请参阅sqlite.org/draft/releaselog/3_34_0.html CRAN 上 RSQLite 的最新版本是 2.2.5,它包含 SQLite 3.35.2,因此它确实包含 substring
猜你喜欢
  • 2023-02-07
  • 2017-03-29
  • 2016-03-04
  • 2018-01-07
  • 2020-10-08
  • 2016-03-04
  • 2013-03-09
相关资源
最近更新 更多