Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python get a list of years

Tags:

python

I need to get the last 5 years in python. I was hoping to do this in once nice neat line. But the best i can come up with is this.

year = datetime.datetime.today().year
YEARS = [year, year-1, year-2, year-3, year-4, year-5]

Is there a nicer way?

like image 521
Mark Avatar asked Nov 28 '22 08:11

Mark


2 Answers

This can help:

>>> range(year, year - 6, -1)
[2016, 2015, 2014, 2013, 2012, 2011]
like image 81
JuniorCompressor Avatar answered Dec 05 '22 15:12

JuniorCompressor


With a list comprehension:

year = datetime.datetime.today().year
YEARS = [year - i for i in range(6)]

or (in Python 2), just use range() directly to produce the list:

year = datetime.datetime.today().year
YEARS = range(year, year - 6, -1)

You can use the latter in Python 3 too, but you'll have to convert to a list with the list() call:

year = datetime.datetime.today().year
YEARS = list(range(year, year - 6, -1))

at which point the list comprehension may well be more readable. In all these expressions, you can inline the datetime.datetime.today().year, but this does mean it'll be called 6 times (for the list comprehension) or twice (for the range()-only approaches).

like image 33
Martijn Pieters Avatar answered Dec 05 '22 15:12

Martijn Pieters