Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract/add days from/to a date?

Tags:

date

r

r-faq

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?

like image 226
Dan Avatar asked Feb 12 '10 20:02

Dan


People also ask

What is the formula to add days to a date?

Enter the number of days to add or subtract in column B. You can enter a negative number to subtract days from your start date, and a positive number to add to your date. In cell C2, enter =A2+B2, and copy down as needed.

How do you subtract days from a date?

Therefore, you can add or subtract days as easy as adding or minus the number of days in Excel. 1. Select a blank cell you will place the calculating result, type the formula =A2+10, and press the Enter key. Note: For subtracting 10 days from the date, please use this formula =A2–10.

How do I automatically add days to a date in Excel?

Type '=' and select the first cell of the column containing the dates you want to add days to (cell A2). Next, type '+' followed by the number of days you want to add. So, if you want to add 15 days, type '+15' in the same cell. This means, your cell H2 should have the formula =A2+15.


2 Answers

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" 
like image 92
Shane Avatar answered Nov 15 '22 23:11

Shane


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.

like image 22
Aniko Avatar answered Nov 16 '22 01:11

Aniko