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?
This can help:
>>> range(year, year - 6, -1)
[2016, 2015, 2014, 2013, 2012, 2011]
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With