首页 > 解决方案 > SQL将时间戳中的秒数转换为整数

问题描述

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

时间栏

输出

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

标签: sqlrcastingtimestamp

解决方案


假数据

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

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

两者substr和别名都将返回字符串的长度substring作为最后一个参数。从文档

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

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

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

推荐阅读