'Python arrow get list of years between date range
I have this function:
def function(start_date_arrow=None,end_date_arrow=None, date_concept=None):
list=[getattr(date, date_concept) for date in arrow.Arrow.range(date_concept, start_date_arrow, end_date_arrow)]
This function works well when iterating over date_concept='month'
and date_concept='day'
. On the other hand, date_concept='year'
only returns a list of one item.
For example:
start_date_arrow= arrow.get('2021-11-05')
end_date_arrow= arrow.get('2022-02-05')
year_list=function(start_date_arrow=start_date_arrow,end_date_arrow=end_date_arrow, date_concept='year')
year_list is [2021]
month_list=function(start_date_arrow=start_date_arrow,end_date_arrow=end_date_arrow, date_concept='month')
month_list is [11, 12, 1, 2]
day_list=function(start_date_arrow=start_date_arrow,end_date_arrow=end_date_arrow, date_concept='day')
day_list is [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
Second and third call are okei, but first one should return [2021,2022] instead of [2021].
Any idea of what is happening in the year call?
Solution 1:[1]
Found the issue. If you use:
start_date_arrow= arrow.get('2021-11-05')
end_date_arrow= arrow.get('2022-02-05')
Year difference between both is less than 1, so it only returns the first one, so to return 2022 in the list end_date_arrow
should be end_date_arrow= arrow.get('2022-11-05')
So I forced with an if
statement the end date to be bigger just by one year, to force the return of both years.
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 | mrc |