Skip to content

Commit

Permalink
Small fix to return correct hdate for leap days (#352)
Browse files Browse the repository at this point in the history
* Small fix to return correct hdate for leap days

* Formatting
  • Loading branch information
raspstephan authored Jun 26, 2023
1 parent e49b169 commit edd742d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
5 changes: 5 additions & 0 deletions weather_dl/download_pipeline/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,8 @@ def download_with_aria2(url: str, path: str) -> None:

def generate_hdate(date: str, subtract_year: str) -> str:
"""Generate a historical date by subtracting a specified number of years from the given date.
If input date is leap day (Feb 29), return Feb 28 even if target hdate is also a leap year.
This is expected in ECMWF API.
Args:
date (str): The input date in the format 'YYYY-MM-DD'.
Expand All @@ -213,6 +215,9 @@ def generate_hdate(date: str, subtract_year: str) -> str:
"""
try:
input_date = datetime.datetime.strptime(date, "%Y-%m-%d")
# Check for leap day
if input_date.month == 2 and input_date.day == 29:
input_date = input_date - datetime.timedelta(days=1)
subtract_year = int(subtract_year)
except (ValueError, TypeError):
logger.error("Invalid input.")
Expand Down
10 changes: 10 additions & 0 deletions weather_dl/download_pipeline/util_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,13 @@ def test_valid_hdate(self):
substract_year = '4'
expected_result = '2016-01-02'
self.assertEqual(generate_hdate(date, substract_year), expected_result)

# Also test for leap day correctness
date = '2020-02-29'
substract_year = '3'
expected_result = '2017-02-28'
self.assertEqual(generate_hdate(date, substract_year), expected_result)

substract_year = '4'
expected_result = '2016-02-28'
self.assertEqual(generate_hdate(date, substract_year), expected_result)

0 comments on commit edd742d

Please sign in to comment.