如何从日期中减去/添加天数?

发布于 2024-08-20 21:44:22 字数 212 浏览 9 评论 0原文

我正在尝试构建文件夹来存储数据拉取。我想用拉取数据的日期来标记文件夹。

前任。我从 mysql 中提取 5 天前的数据,我想将文件夹命名为 5 天前的日期。

MySQL可以轻松处理日期运算。我不确定 R 到底是如何做到的。我应该在 POSIXct 中减去适当的秒数,然后转换为 POSIXlt 以将文件夹命名为 MM_DD_YYYY 吗?

或者有更好的方法吗?

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.

Ex. I pull 5 days ago data from mysql i want to name the folder the date from 5 days ago.

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?

Or is there a better way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

铁轨上的流浪者 2024-08-27 21:44:22

只需减去一个数字:

> as.Date("2009-10-01")
[1] "2009-10-01"
> as.Date("2009-10-01")-5
[1] "2009-09-26"

由于 Date 类只有天,因此您可以对其进行基本算术运算。

如果你出于某种原因想使用 POSIXlt,那么你可以使用它的插槽:

> 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"

Just subtract a number:

> as.Date("2009-10-01")
[1] "2009-10-01"
> as.Date("2009-10-01")-5
[1] "2009-09-26"

Since the Date class only has days, you can just do basic arithmetic on it.

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"
北城挽邺 2024-08-27 21:44:22

答案可能取决于您的日期采用的格式,但这里是使用 Date 类的示例:

dt <- as.Date("2010/02/10")
new.dt <- dt - as.difftime(2, unit="days")

您甚至可以使用不同的单位,例如周。

The answer probably depends on what format your date is in, but here is an example using the Date class:

dt <- as.Date("2010/02/10")
new.dt <- dt - as.difftime(2, unit="days")

You can even play with different units like weeks.

冰之心 2024-08-27 21:44:22

当然有一个 lubridate 解决方案:

library(lubridate)
date <- "2009-10-01"

ymd(date) - 5
# [1] "2009-09-26"

相同:

ymd(date) - days(5)
# [1] "2009-09-26"

与其他时间格式

ymd(date) - months(5)
# [1] "2009-05-01"

ymd(date) - years(5)
# [1] "2004-10-01"

ymd(date) - years(1) - months(2) - days(3)
# [1] "2008-07-29"

There is of course a lubridate solution for this:

library(lubridate)
date <- "2009-10-01"

ymd(date) - 5
# [1] "2009-09-26"

is the same as

ymd(date) - days(5)
# [1] "2009-09-26"

Other time formats could be:

ymd(date) - months(5)
# [1] "2009-05-01"

ymd(date) - years(5)
# [1] "2004-10-01"

ymd(date) - years(1) - months(2) - days(3)
# [1] "2008-07-29"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文