简体   繁体   English

在R中将日期转换为as.POSIXct,并减去两个日期

[英]Converting date to as.POSIXct in R and it subtracts two dates

I'm trying to calculate a date - 1 (basically the day before the date) in R and when it converts it to a POSIXct it seems to subtract another date? 我正在尝试计算日期-R中的1(基本上是日期的前一天),当它将其转换为POSIXct时,似乎要减去另一个日期?

The column is of type POSIXct: 该列的类型为POSIXct:

class(df$Date)
[1] "POSIXct" "POSIXt" 

Here's the initial value: 这是初始值:

> df[12,"Date"]
[1] "2016-03-09 EST"

If I just do as.Date and subtract one it works fine: 如果我只做as.Date并减去一个,它就可以正常工作:

as.Date(df[12,"Date"]-1, tz="EST")
[1] "2016-03-08"

But I'm saving it back to the same column so it converts is back to as.POSIXct automatically (I think). 但是我将其保存回同一列,因此它会自动转换回as.POSIXct。 And then I end up with March 7 in that column. 然后,我在该专栏中以3月7日结束。 And 7 pm. 晚上7点。 If I type it out here I get this: 如果在这里输入,我会得到:

as.POSIXct(as.Date(df[12,"Date"]-1, tz="EST"))
[1] "2016-03-07 19:00:00 EST"

I've tried using America/New York for the tz. 我曾尝试使用America / New York作为tz。 I've tried the as.Date around just the df[12,"Date"] or around the whole thing including the -1... I have no clue what to do! 我已经尝试过df [12,“ Date”]周围的as.Date或包括-1在内的整个东西。我不知道该怎么办!

Thanks! 谢谢!

Use as.difftime to take away amounts specified in units of time. 使用as.difftime带走以时间单位指定的数量。 It will work consistently regardless of your data being in Date or POSIXct formats. 无论您的数据是Date还是POSIXct格式,它都将持续工作。 Eg: 例如:

This fails as you described: 如您所述,此操作失败:

x <- as.POSIXct(c("2016-03-09","2016-03-10"), tz="US/Eastern")
#[1] "2016-03-09 EST" "2016-03-10 EST"
x[1] <- as.Date(x[1]-1, tz="US/Eastern")
#[1] "2016-03-07 19:00:00 EST" "2016-03-10 00:00:00 EST"

This works: 这有效:

x <- as.POSIXct(c("2016-03-09","2016-03-10"), tz="US/Eastern")
#[1] "2016-03-09 EST" "2016-03-10 EST"
x[1] <- x[1] - as.difftime(1, units="days")
#[1] "2016-03-08 EST" "2016-03-10 EST"

If you don't want to do what Frank mentioned in the comments, 如果您不想做弗兰克在评论中提到的事情,

You should consider using strptime instead of as.POSIXct 您应该考虑使用strptime而不是as.POSIXct

To ensure it returns in a POSIXct format use: 为了确保它以POSIXct格式返回, POSIXct使用:

strptime(df[12,"Date"]-1,tz="EST",format="%Y-%m-%d")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM