如何通过循环数字形成日期?

时间:2019-03-20 10:20:19

标签: r

我正在抓取页面,链接的一部分是日期的变化。

我需要执行循环操作以更改链接中的日期,然后才能抓取所需的所有页面。

链接为:例如https://www.dr.dk/nyheder/allenyheder/politik/20032019

我需要从01012019到20032019的所有链接。

    # Defining URL
    dr.url <- "https://www.dr.dk/nyheder/allenyheder/politik/"

# Looping dates
for (year 2019:2019){
  for (month 1:12){
    if(month %in% c(1,3,5,7,8,10,12)){
       length.POSIXlt(31)
    } else if (month==2){
      length.POSIXlt(28)
    } else {
      length.POSIXlt(30)
    }

    for (day in 1:) {
      if(str_length(month) == 1) month <- paste0(0,month)
      if(str_length(day) == 1) day <- paste0(0,day)

      final.date <- paste0(day,month,year)

      final.url <- paste0(dr.url, final.date)
    }
  }
}

这不起作用。

还有更好的主意吗?或至少有效的东西?

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以尝试使用日期格式来解决此问题。

Enddate = as.Date("20032019", format = '%d%m%Y')
Startdate = as.Date("01012019", format = '%d%m%Y')

Dates = seq(Startdate, Enddate, by = "days")

Dates = format(Dates, "%d%m%Y")

> Dates
 [1] "01012019" "02012019" "03012019" "04012019" "05012019" "06012019" "07012019" "08012019" "09012019" "10012019"
[11] "11012019" "12012019" "13012019" "14012019" "15012019" "16012019" "17012019" "18012019" "19012019" "20012019"
[21] "21012019" "22012019" "23012019" "24012019" "25012019" "26012019" "27012019" "28012019" "29012019" "30012019"
[31] "31012019" "01022019" "02022019" "03022019" "04022019" "05022019" "06022019" "07022019" "08022019" "09022019"
[41] "10022019" "11022019" "12022019" "13022019" "14022019" "15022019" "16022019" "17022019" "18022019" "19022019"
[51] "20022019" "21022019" "22022019" "23022019" "24022019" "25022019" "26022019" "27022019" "28022019" "01032019"
[61] "02032019" "03032019" "04032019" "05032019" "06032019" "07032019" "08032019" "09032019" "10032019" "11032019"
[71] "12032019" "13032019" "14032019" "15032019" "16032019" "17032019" "18032019" "19032019" "20032019"

答案 1 :(得分:0)

您可以使用以下代码:

heap out of memory