如何找到R中两个日期之间的天数和星期数?
在数据分析中,时间序列是我们必须处理的常见数据之一,它可能还包含日期数据以及其他变量。我们可能希望找到两次之间的差异,以检查更改了时间序列的天数或周数。这可以通过difftime函数轻松完成。
示例
> 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