从 POSIXct 对象中减去正好一年 [英] Subtract exactly one year from a POSIXct object
问题描述
假设我们有这个日期2014-05-11 14:45:00 UTC".我想在2013-05-11 14:45:00 UTC"之前获得 1 年的确切 POSIXct 对象.
lets say we have this date "2014-05-11 14:45:00 UTC". I would like to get the exact POSIXct object for 1 year before so "2013-05-11 14:45:00 UTC".
我的第一个想法是创建一个全新的 POSIXct 对象,方法是从年份位中减去一个并将其与字符串的其余部分一起粘贴,然后使用该字符串创建一个新的 POSIXct 对象,如下所示:
My first thought is to create a whole new POSIXct object by subtracting one from the year bit and pasting it together with the remainder of the string and then creating a new POSIXct object with that string like so:
time <- as.POSIXct("2014-05-11 14:45:00 UTC",tz="UTC",origin="1970-01-01")
newTime <- as.POSIXct(paste(as.character(as.numeric(substr(time,1,4)) - 1),substr(time,5,19),sep=""),tz="UTC",origin="1970-01-01")
这很好用(闰年除外!)但问题是我需要在一个大的 data.table 中为每一行执行此操作,最好将结果放回 data.table 中.有没有其他方法可以从这样的对象中减去一年?
this works fine (except in case of leap years!) but the thing is I need to do this in a large data.table for each row and preferably put the results right back in data.table. Is there any other way of subtracting a year off an object like this?
我需要将它应用到像这样的 data.table 中:
Some extra I need to apply this to a data.table like this one:
Time
1: 1349206200
2: 1349207100
3: 1349208000
4: 1349208900
5: 1349209800
6: 1349210700
7: 1349211600
8: 1349212500
9: 1349213400
10: 1349214300
11: 1349215200
但是当我这样做时会发生这种情况:
but this happens when I do:
SOdata[,Time:=as.numeric(as.POSIXct(paste(as.character(as.numeric(substr(Time,1,4)) - 1),substr(Time,5,19),sep=""),tz="UTC",origin="1970-01-01"))]
Error in as.POSIXlt.character(x, tz, ...) :
character string is not in a standard unambiguous format
我猜我需要使用类似 lapply 的东西,但是在使用该函数时我总是弄乱语法.那么有人知道怎么做吗?
I am guessing I need to use something like lapply, but I always mess up syntax when using that function. So does anyone know how?
推荐答案
我还没有测试过其他答案,但是无论闰年如何,以下应该都能正常工作:
I haven't tested the other answers, but the following should work as required regardless of leap years:
time <- as.POSIXct("2014-05-11 14:45:00 UTC",tz="UTC",origin="1970-01-01")
time <- as.POSIXlt(time)
time$year <- time$year - 1
time <- as.POSIXct(time)
#[1] "2013-05-11 14:45:00 UTC"
以 Gabor 的闰年为例:
With Gabor's leap year example:
time <- as.POSIXct("2012-02-29 14:45:00 UTC",tz="UTC",origin="1970-01-01")
time <- as.POSIXlt(time)
time$year <- time$year - 1
time <- as.POSIXct(time)
#[1] "2011-03-01 14:45:00 UTC"
这篇关于从 POSIXct 对象中减去正好一年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!