如何从/向日期减去/添加天数? [英] How to subtract/add days from/to a date?
问题描述
我正在尝试构建文件夹来存储数据拉取.我想用拉取数据的日期标记文件夹.
I'm trying to build folders to store data pulls. I want to label the folders with the day of that data in the pull.
例如.我从 mysql 中提取 5 天前的数据,我想将文件夹命名为 5 天前的日期.
Ex. I pull 5 days ago data from mysql i want to name the folder the date from 5 days ago.
MySQL 可以轻松处理日期算法.我不确定 R 到底是怎么做的.我应该在 POSIXct 中减去适当的秒数,然后转换为 POSIXlt 来命名文件夹 MM_DD_YYYY 吗?
MySQL can easily handle date arithmetic. I'm not sure exactly how R does it. Should i just subtract the appropriate number of seconds in POSIXct and then convert to POSIXlt to name the folder MM_DD_YYYY?
或者有更好的方法吗?
推荐答案
只需减去一个数字:
> as.Date("2009-10-01")
[1] "2009-10-01"
> as.Date("2009-10-01")-5
[1] "2009-09-26"
由于 Date
类只有几天,您可以对其进行基本的算术运算.
Since the Date
class only has days, you can just do basic arithmetic on it.
如果您出于某种原因想使用 POSIXlt,那么您可以使用它的插槽:
If you want to use POSIXlt for some reason, then you can use it's slots:
> a <- as.POSIXlt("2009-10-04")
> names(unclass(as.POSIXlt("2009-10-04")))
[1] "sec" "min" "hour" "mday" "mon" "year" "wday" "yday" "isdst"
> a$mday <- a$mday - 6
> a
[1] "2009-09-28 EDT"
这篇关于如何从/向日期减去/添加天数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!