gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:19:41 26 4
gpt4 key购买 nike

大家好,我在将时间戳转换为 POSIXlt 时遇到问题,稍后需要从这个时间戳中提取 Year,month,dayofmoth,hour,min,sec

    2015-12-01 00:04:39 is my timestamp

这是我的尝试

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$timestamp' 转换为类“POSIXlt”

稍后我需要找出 Year,month,dayofmonth,hors,min,sec 因为我有这个片段

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")

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

 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**

我怎样才能摆脱这个错误,我们将不胜感激。谢谢

最佳答案

您可以使用 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

关于R POSIXlt 时间戳转换不知道如何将 'df1$timestamp' 转换为类 “POSIXlt”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38896257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com