如何从日期中减去/增加日期? [英] How to subtract/add days from/to a date?

查看:143
本文介绍了如何从日期中减去/增加日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立文件夹来存储数据提取.我想在下拉列表中用数据的日期标记文件夹.

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

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