Mark
Mark

Reputation: 2542

Python get a list of years

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?

Upvotes: 4

Views: 14550

Answers (5)

Larry Lustig
Larry Lustig

Reputation: 51000

You could use a list comprehension.

For example:

 years = [datetime.datetime.today().year - index for index in range(6)]

This loops through the numbers 0-5, and subtracts the number from this year.

Upvotes: -1

Martijn Pieters
Martijn Pieters

Reputation: 1123350

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).

Upvotes: 8

Luis González
Luis González

Reputation: 3559

 years_back = 5
 year = datetime.datetime.today().year
 YEARS = [year - i for i in range(years_back+1)]

Upvotes: 1

Mad Physicist
Mad Physicist

Reputation: 114440

There is, but it will be the same number of lines. You can use a list comprehension to generate the offsets so that you do not have to type them all manually. Especially useful if the number changes:

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

Note the range(6) since you are actually asking for a list of 6 items if you include this year (year - 0).

Upvotes: 1

JuniorCompressor
JuniorCompressor

Reputation: 20025

This can help:

>>> range(year, year - 6, -1)
[2016, 2015, 2014, 2013, 2012, 2011]

Upvotes: 23

Related Questions