0

I am trying to write out year ranges in the form 2010-11, 2011-12 etc. as strings. The code I am using right now is:

date = ['200' + str(x) + '-' + str(x+1) for x in range(1,9)] + ['20' + str(x) + '-' + str(x+1) for x in range(10,16)]

which outputs

['2001-2', '2002-3', '2003-4', '2004-5', '2005-6', '2006-7', '2007-8', '2008-9', '2010-11', '2011-12', '2012-13', '2013-14', '2014-15', '2015-16']

How can I write this in a single line of code instead of separating into the two cases where the years are <10, >10?

Edit 7/5/20: Have changed the wording to fix opinion-based question.

Zarathustra
  • 145
  • 1
  • 7

4 Answers4

1

Years are numbers; just add them normally instead of trying to reimplement integer addition as a string operation. :) Also, f-strings are a lot more concise for this sort of thing than converting to string and concatenating!

>>> [f"{2000+y}-{y+1:02d}" for y in range(1, 20)]
['2001-02', '2002-03', '2003-04', '2004-05', '2005-06', '2006-07', '2007-08', '2008-09', '2009-10', '2010-11', '2011-12', '2012-13', '2013-14', '2014-15', '2015-16', '2016-17', '2017-18', '2018-19', '2019-20']
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • Thanks @Samwise. How would I get a '0' in front of the years which have no tens-units (ie. '2001-02' instead of '2001-2')? – Zarathustra May 06 '20 at 22:21
  • 1
    Just do `{y+1:02d}` to say that you want the number to be zero-padded with two digits. Will edit that into the answer. :) – Samwise May 06 '20 at 22:53
1

Using f-strings is more readable:

[f'200{x}-{x+1}' for x in range(1,9)]

You can find out more about them here

1

You can try pandas.date_range https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html

You can also look into this forum, which I think is probably what you're looking for. datetime to string with series in python pandas

Dani56
  • 372
  • 1
  • 2
  • 7
1

You can use python string formatting to specify a fixed length:

['2{:003d}-{:02d}'.format(x, x+1) for x in range(0,20)]

outputs

['2000-01', '2001-02', '2002-03', '2003-04', '2004-05', '2005-06', '2006-07', '2007-08', '2008-09', '2009-10', '2010-11', '2011-12', '2012-13', '2013-14', '2014-15', '2015-16', '2016-17', '2017-18', '2018-19', '2019-20']
Zeke
  • 11
  • 4