R POSIXlt时间戳转换不知道如何将'df1 $ timestamp'转换为类“POSIXlt”

时间:2016-08-11 12:21:33

标签: r datetime sparkr

大家好我在将时间戳转换为POSIXlt时遇到问题,稍后从此时间戳开始需要提取年,月,日,小时,分钟,秒

getwd()
rm(list=ls())
library(ggplot2)
library(plyr)
library(reshape)
library(scales)
library(gridExtra)
library(SparkR)

Sys.setenv(SPARK_HOME="/usr/local/spark").libPaths(c(file.path(Sys.getenv("SPARK_HOME"), "R", "lib"), .libPaths()))

sc <- sparkR.init(master="local","RwordCount")
args <- commandArgs(trailing = TRUE)

sqlContext <- sparkRSQL.init(sc)

df1 <- read.df(sqlContext, "hdfs://master:9000/test.csv",  header='true', source = "com.databricks.spark.csv", inferSchema='true', stringsAsFactors = F)


 if("timestamp" %in% colnames(df1)){
     df1$pTime <- as.POSIXlt(df1$timestamp, format= "%Y-%m-%d  %H:%M:%S") 
  }else {
     df1$pTime <- as.POSIXlt(df1$Timestamp, format= "%Y-%m-%d %H:%M:%S")
}

这是我的尝试

df1$Year <- df1$pTime$year-100  #Year
df1$Month <- df1$pTime$mon+1  #Month 1-12
df1$Day <-  df1$pTime$mday  #day of month
df1$Hour <- df1$pTime$hour  #0â??23: hours
df1$Min <- df1$pTime$min
df1$Sec <- df1$pTime$sec
df1$WeekOfYear <- strftime(df1$pTime, format="%W")

但在此处收到错误不知道如何将'df1 $ timestamp'转换为“POSIXlt”类

稍后我需要找出年份,月份,日期,月份,小时,秒,因为我有这个片段

 bin/spark-submit --packages com.databricks:spark-csv_2.11:1.3.0  /home/script/analysis.R 

 **Error in as.POSIXlt.default(df1$timestamp, format = "%Y-%m-%d %H:%M:%S") : 
  do not know how to convert 'df1$timestamp' to class “POSIXlt”
  Calls: as.POSIXlt -> as.POSIXlt.default
  Execution halted**

我正在使用以下语法执行上面的脚本,

fullcalendar

我如何摆脱错误,任何帮助将不胜感激。 感谢

4 个答案:

答案 0 :(得分:1)

您可以通过

提取部分日期时间值
x <- Sys.time()
format(x, format="%Y")
例如,

。参见

?strptime

所有选项。

我无法重建你问题的第一部分。你得到的错误信息是什么?

答案 1 :(得分:1)

您可以使用as.POSIXct

转换时间戳
x <- as.POSIXct("2015-12-01 00:04:39")

然后使用lubridate包,您可以提取所有信息

library(lubridate)

year(x)
#[1] 2015
month(x)
#[1] 12
day(x)
#[1] 1
hour(x)
#[1] 0
minute(x)
#[1] 4
second(x)
#[1] 39

答案 2 :(得分:1)

首先,您可以在不使用ifelse案例

的情况下使用index.frame进行索引
df1[colnames(df1) %in% "timestamp"]

转换整个格式为2015-12-01 00:04:39

的列
as.POSIXlt(strptime(as.character(df1[colnames(df1) %in% "timestamp"]), 
                     format = "%Y-%m-%d %H:%M:%S"),
           format = "%Y-%m-%d %H:%M:%S")

答案 3 :(得分:0)

我在数据框中具有'trans_dtime'列类型 string 。我已使用 SparkR

'trans_dtime'列转换为时间戳类型
makeStyles-keyframes-flicker-4043

printSchema(df)
root
 |-- col1: string (nullable = true)
 |-- trans_dtime: string (nullable = true)

df$trans_dtime <- from_utc_timestamp(date_format(df$trans_dtime, "YYYY-MM-dd HH:mm:ss"), "GMT")

希望它会对您有所帮助。 :)