lea*_*909 7 postgresql datetime r amazon-redshift dplyr
我的数据中有时间戳,列Timelocal格式如下:
2015-08-24T00:02:03.000Z
Run Code Online (Sandbox Code Playgroud)
通常,我使用以下行转换此格式以将其转换为我可以使用的日期格式.
timestamp2 = "2015-08-24T00:02:03.000Z"
timestamp2_formatted = strptime(timestamp2,"%Y-%m-%dT%H:%M:%S",tz="UTC")
# also works for dataframes (my main use of it)
df$TimeNew = strptime(df$TimeLocal,"%Y-%m-%dT%H:%M:%S",tz="UTC")
Run Code Online (Sandbox Code Playgroud)
这在我的机器上工作正常.问题是,我现在正在使用更大的数据帧.它位于Redshift集群上,我使用RPostgreSQL包访问它.我正在使用dplyr来操作数据,因为在线文档表明它与RPostgreSQL很好地配合.
它似乎确实如此,除了转换日期格式.我想将字符格式转换为时间格式.Timelocal将其作为"varchar"读入Redshift.因此,R将其解释为字符字段.
我尝试过以下方法:
library(dplyr)
library(RPostgreSQL)
library(lubridate)
Run Code Online (Sandbox Code Playgroud)
尝试1 - 使用简单的dplyr语法
mutate(elevate, timelocalnew = fast_strptime(timelocal, "%Y-%m-%dT%H:%M:%S",tz="UTC"))
Run Code Online (Sandbox Code Playgroud)
尝试2 - 使用来自其他在线参考代码的dplyr语法
elevate %>%
mutate(timelocalnew = timelocal %>% fast_strptime("%Y-%m-%dT%H:%M:%S",tz="UTC") %>% as.character()) %>%
filter(!is.na(timelocalnew))
Run Code Online (Sandbox Code Playgroud)
尝试3 - 使用strptime代替 fast_strptime
elevate %>%
mutate(timelocalnew = timelocal %>% strptime("%Y-%m-%dT%H:%M:%S",tz="UTC") %>% as.character()) %>%
filter(!is.na(timelocalnew))
Run Code Online (Sandbox Code Playgroud)
我正在尝试从这里调整代码:http://www.markhneedham.com/blog/2014/12/08/r-dplyr-mutate-with-strptime-incompatible-sizewrong-result-size/
我的尝试是错误的,因为:
Error in postgresqlExecStatement(conn, statement, ...) :
RS-DBI driver: (could not Retrieve the result : ERROR: syntax error at or near "AS"
LINE 1: ...CAST(STRPTIME("timelocal", '%YSuccess2048568264T%H%M?????', 'UTC' AS "tz") A...
^
)
In addition: Warning messages:
1: In postgresqlQuickSQL(conn, statement, ...) :
Could not create executeSELECT count(*) FROM (SELECT "timelocal", "timeutc", "zipcode", "otherdata", "country", CAST(STRPTIME("timelocal", '%Y%m%dT%H%M%S', 'UTC' AS "tz") AS TEXT) AS "timelocalnew"
FROM "data") AS "master"
2: Named arguments ignored for SQL STRPTIME
Run Code Online (Sandbox Code Playgroud)
似乎strptime与RPostgreSQL不兼容.这是正确的解释吗?如果是这样,这是否意味着如果数据在Redshift上,则无法处理R中的日期格式?我检查了RPostgreSQL包文档,但没有看到任何与指定时间格式相关的内容.
非常感谢有关使用dplyr和RpostgreSQL正确格式化日期时间列的任何建议.
小智 0
下面的方法有效吗?
as.Date(strptime(timelocal,format = "%YYYY/%MM/%DD %H:%M:%OS"),tz="UTC")
Run Code Online (Sandbox Code Playgroud)