How to find the number of days and number of weeks between two dates in R?

R ProgrammingServer Side ProgrammingProgramming

In data analysis, time series is one of the common data we have to deal with and it might also contain dates data along with other variables. We might want to find the difference between two times to check how many days or weeks have changed the time series. This can be easily done with the help of difftime function.

Example

> difftime(strptime("25/07/2021", format = "%d/%m/%Y"),
+ strptime("25/07/2020", format = "%d/%m/%Y"),units="weeks")
Time difference of 52.14286 weeks
> difftime(strptime("25.07.2021", format = "%d.%m.%Y"),
+ strptime("25.07.2020", format = "%d.%m.%Y"),units="weeks")
Time difference of 52.14286 weeks
> difftime(strptime("25.07.2021", format = "%d.%m.%Y"),
+ strptime("25.07.2020", format = "%d.%m.%Y"))
Time difference of 365 days
> difftime(strptime("01.01.2021", format = "%d.%m.%Y"),
+ strptime("25.07.2020", format = "%d.%m.%Y"))
Time difference of 160 days
> difftime(strptime("01.01.2021", format = "%d.%m.%Y"),
+ strptime("25.07.2020", format = "%d.%m.%Y"),units="weeks")
Time difference of 22.85714 weeks
> difftime(strptime("01.01.2050", format = "%d.%m.%Y"),
+ strptime("01.01.2020", format = "%d.%m.%Y"))
Time difference of 10958 days
> difftime(strptime("01.01.2050", format = "%d.%m.%Y"),
+ strptime("01.01.2020", format = "%d.%m.%Y"),units="weeks")
Time difference of 1565.429 weeks
> difftime(strptime("01.01.2030", format = "%d.%m.%Y"),
+ strptime("01.01.2020", format = "%d.%m.%Y"),units="weeks")
Time difference of 521.8571 weeks
> difftime(strptime("01.01.2030", format = "%d.%m.%Y"),
+ strptime("01.01.2020", format = "%d.%m.%Y"))
Time difference of 3653 days
> difftime(strptime("25/12/2021", format = "%d/%m/%Y"),
+ strptime("01/01/2021", format = "%d/%m/%Y"),units="weeks")
Time difference of 51.14286 weeks
> difftime(strptime("25/12/2021", format = "%d/%m/%Y"),
+ strptime("01/01/2021", format = "%d/%m/%Y"))
Time difference of 358 days
> difftime(strptime("01/01/3000", format = "%d/%m/%Y"),
+ strptime("01/01/2000", format = "%d/%m/%Y"))
Time difference of 365243 days
> difftime(strptime("01/01/3000", format = "%d/%m/%Y"),
+ strptime("01/01/2000", format = "%d/%m/%Y"),units="weeks")
Time difference of 52177.57 weeks
> difftime(strptime("01/01/0001", format = "%d/%m/%Y"),
+ strptime("25/07/2020", format = "%d/%m/%Y"))
Time difference of -737630 days
> difftime(strptime("01/01/0001", format = "%d/%m/%Y"),
+ strptime("25/07/2020", format = "%d/%m/%Y"),units="weeks")
Time difference of -105375.7 weeks
raja
Published on 11-Aug-2020 09:18:57
Advertisements