简体   繁体   English

计算两个日期之间的差异

[英]Calculate difference between two dates

My dates in the txt file are like, start date= "011589" and end date is "122390". 我在txt文件中的日期是,开始日期=“ 011589”,结束日期是“ 122390”。 How can I calculate the duration using R. 如何使用R计算持续时间。

I tried mydata$startdate=as.Date(mydata$startdate) but it did not work 我尝试了mydata $ startdate = as.Date(mydata $ startdate),但是没有用

This can be done using format 这可以使用format来完成

Start <- as.Date("011589", "%m%d%y")
Start
#[1] "1989-01-15"
End <- as.Date("122390", "%m%d%y")
End
#[1] "1990-12-23"

If we need the difference in 'days' 如果我们需要“天数”方面的差异

as.vector(difftime(End, Start, units='days'))
#[1] 707

Or just use - to get the difference in 'days'. 或只是使用-获得“天数”的差异。 The above method is more flexible as we can specify the units 上面的方法更灵活,因为我们可以指定units

as.vector(End-Start)
#[1] 707

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM