如何在r中设置posixlt中的日、月和年?
我必须在数据框中确定一个日期。日期为“16/12/2006”,时间为“17:24:00”。我想构造一个包含日期和时间的posixlt。我试过:如何在r中设置posixlt中的日、月和年?,r,date,strptime,posixlt,R,Date,Strptime,Posixlt,我必须在数据框中确定一个日期。日期为“16/12/2006”,时间为“17:24:00”。我想构造一个包含日期和时间的posixlt。我试过: fixTime2<-function(date,time) { # replaces the date in time with the parameter date. fixed<-time fixed$mon<-as.numeric(format(date,"%m")) fixed$mday<-as.n
fixTime2<-function(date,time) { # replaces the date in time with the parameter date.
fixed<-time
fixed$mon<-as.numeric(format(date,"%m"))
fixed$mday<-as.numeric(format(date,"%d"))
fixed$year<-as.numeric(format(date,"%Y"))-1900
return(fixed)
}
testFixTime2<-function() {
date<-as.Date("16/12/2006", format = "%d/%m/%Y")
str(date)
time<-strptime("17:24:00","%H:%M:%S")
str(time)
fixed<-fixTime2(date,time)
str(fixed)
return(fixed)
}
fixTime2如果您有单独的字符串,那么
as.POSIXlt(paste(date, time), format="%d/%m/%Y %H:%M:%S")
应该有用。例如:
as.POSIXlt(paste("16/12/2006", "17:24:00"), format="%d/%m/%Y %H:%M:%S")
# [1] "2006-12-16 17:24:00"
关于第二点,$month
和$day
是不可用的属性。您可以通过以下内容查看可用的属性:
dput(as.POSIXlt(Sys.time()))
# structure(list(sec = 48.7993450164795, min = 17L, hour = 0L,
# mday = 18L, mon = 6L, year = 118L, wday = 3L, yday = 198L,
# isdst = 1L, zone = "PDT", gmtoff = -25200L), .Names = c("sec",
# "min", "hour", "mday", "mon", "year", "wday", "yday", "isdst",
# "zone", "gmtoff"), class = c("POSIXlt", "POSIXt"), tzone = c("",
# "PST", "PDT"))
显示您真正需要的是$mon
和$mday
as.POSIXlt(“16/12/2006 17:24:00”,format=“%d/%m/%Y%H:%m:%S”)
工作正常,我是否遗漏了什么?(甚至as.POSIXlt(粘贴(“16/12/2006”,“17:24:00”),format=“%d/%m/%Y%H:%m:%S”)
如果它们分开来的话。)哦。。。也许dput(as.POSIXlt(Sys.time())
会告诉您关于$mon
和$mday
。当日期和时间是字符串时,as.POSIXlt(sprintf(“%s%s”,date,time)格式=“%d/%m/%Y%H:%m:%s”)可以正常工作。发一个帖子,我会查一查。
as.POSIXlt(paste("16/12/2006", "17:24:00"), format="%d/%m/%Y %H:%M:%S")
# [1] "2006-12-16 17:24:00"
dput(as.POSIXlt(Sys.time()))
# structure(list(sec = 48.7993450164795, min = 17L, hour = 0L,
# mday = 18L, mon = 6L, year = 118L, wday = 3L, yday = 198L,
# isdst = 1L, zone = "PDT", gmtoff = -25200L), .Names = c("sec",
# "min", "hour", "mday", "mon", "year", "wday", "yday", "isdst",
# "zone", "gmtoff"), class = c("POSIXlt", "POSIXt"), tzone = c("",
# "PST", "PDT"))