如何修改Google Apps Script实现CSV数据未来15天范围过滤?
Solution
To add the filter for data within 15 days from the current date (while retaining your existing 2-day lookback and capping future data at 15 days out), you'll need to:
- Calculate the upper date limit (15 days from today)
- Update the filter condition to include this new upper bound
Here's the modified script with these changes, plus clarity improvements for date calculations:
function FiveThirtyEight() { var spreadsheet = SpreadsheetApp.getActive(); spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Import CSV Data'), true); var sheet = spreadsheet.getActiveSheet(); sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns()).activate(); spreadsheet.getActiveRangeList().clear({contentsOnly: true, skipFilteredRows: true}); var url = "https://projects.fivethirtyeight.com/soccer-api/club/spi_matches.csv"; var data = UrlFetchApp.fetch(url).getContentText(); var csv = Utilities.parseCsv(data); // Normalize dates to start of day (ignore time components for accurate comparison) var MILLIS_PER_DAY = 1000 * 60 * 60 * 24; // 1 full day in milliseconds (fixed from original 2-day value) var now = new Date(); now.setHours(0, 0, 0, 0); // Calculate our date bounds var twoDaysAgo = new Date(now.getTime() - 2 * MILLIS_PER_DAY); // Keep data from 2 days ago onwards var fifteenDaysFromNow = new Date(now.getTime() + 15 * MILLIS_PER_DAY); // Cap data at 15 days in the future // Filter rows: skip header, keep only dates within our desired range var values = csv.filter(function(e, i) { var temp = new Date(e[0]); temp.setHours(0, 0, 0, 0); // Normalize CSV date to start of day return i > 0 && temp.getTime() >= twoDaysAgo.getTime() && temp.getTime() <= fifteenDaysFromNow.getTime(); }); values.unshift(csv[0]); // Add back the header row sheet.getRange(1, 1, values.length, values[0].length).setValues(values); spreadsheet.getRange('Import CSV Data!H:J').activate(); spreadsheet.getActiveRangeList().setNumberFormat('0.00%'); }
Key Changes Explained:
- Fixed
MILLIS_PER_DAY: The original variable was misleadingly named (it represented 2 days instead of 1). Now it correctly equals one day's worth of milliseconds, making date adjustments easier to read and modify later. - Added
fifteenDaysFromNow: This variable calculates the cutoff date 15 days after today, normalized to the start of the day to avoid time-related comparison errors. - Updated Filter Condition: The
filterfunction now checks that the row's date is both at least 2 days old and no more than 15 days in the future. This removes the outdated 2020 data and any future matches beyond your desired window.
内容的提问来源于stack exchange,提问作者Digital Farmer
相关产品推荐
相关产品推荐

