Keva161
Keva161

Reputation: 2693

Digits to month year?

Is there is easy way to turn digits that represent the month and year into text?

So for example:

1208
109
209
309
409

Would be:

December 2008
January 2009
February 2009
March 2009
April 2009

The only way I can think of doing it currently is via a series of if/else statements.

Upvotes: 4

Views: 60

Answers (1)

alecxe
alecxe

Reputation: 473893

Sure, the idea is to:

  • convert the numbers to strings
  • use .strptime() to load strings into datetime objects
  • use .strftime() to dump datetimes back to strings in a desired format (%B %Y in your case)

Demo:

In [1]: l = [1208, 109, 209, 309, 409]

In [2]: [datetime.strptime(str(item), "%m%y").strftime("%B %Y") for item in l]
Out[2]: ['December 2008', 'January 2009', 'February 2009', 'March 2009', 'April 2009']

Upvotes: 6

Related Questions