'How can I realize Act / Act Convention in Python?
If there are two given dates(e.g., from Oct 12, 2016 to Nov 21, 2019). Based on the Act/Act Convention, how can I calculate the amount of days by the "While" or "IF" loop?
Solution 1:[1]
You can use datetime module, i.e.:
from datetime import datetime
df = "%b %d, %Y"
start = datetime.strptime('Oct 12, 2016', df)
end = datetime.strptime('Nov 21, 2019', df)
diff = end - start
print (diff.days)
# 1135
Solution 2:[2]
The fundamental rule is for days fall in a leap year you divide by 366 and for the rest you devide by 365.
Let me use the following example. date1 = datetime(2020, 5, 8) date2 = datetime(2021, 2, 26)
- For the starting year 2020, which is a leap year, the REMAINING days should be divided by 366 to reflect ACT/ACT convention. For the ending year 2021, the PASSED days to date should be divided by 365.
So basically it becomes (datetime(2020.12.31) - datetime(2020, 5, 8)).days / 366 + (datetime(2021, 2, 26) - datetime(2021, 1, 1)).days / 365
- Expand on above example, assume date2 = datetime(2025, 2, 26). There are more years in between, i.e. [2020, 2021, 2022, 2023, 2024, 2025]. But the middle years should all count as one, and the tricky part sill remains in handling the starting and ending year.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Pedro Lobito |
Solution 2 |