从POSIXct对象中减去一年 [英] Subtract exactly one year from a POSIXct object

查看:83
本文介绍了从POSIXct对象中减去一年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有这个日期2014-05-11 14:45:00 UTC。我想获得准确的POSIXct对象1年之前,因此2013-05-11 14:45:00 UTC。

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?

一些额外的我需要应用这个数据表,像这样:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆