-1

I have a data set where one of the variable is in format 'mm-yy' as below.

0    Feb-94
1    Oct-00
2    Jun-00
3    Jan-85
4    Dec-96
........etc

I want to change it to a format so that I can calculate how many months between, say Feb-94, and this month (Aug-2015). I am using Python 2.7. If there is no direct conversion possible, could anybody give me a clue (code snippet perhaps) as to how to efficiently perform this?

MattDMo
  • 100,794
  • 21
  • 241
  • 231
user62198
  • 1,744
  • 2
  • 13
  • 17
  • What have you tried so far? Have you tried looking at, perhaps, the `datetime` module? – MattDMo Aug 30 '15 at 01:32
  • I tried to split it by '-' and then convert the month to numbers, for example, Feb to 02 and so forth. But it is getting difficult as I need to convert 94 to 1994 and 01 to 2001 and so on. So it is becoming clunky. I am wondering is there a more easier way of doing it ? I am new to Python, so may be missing modules which could help me. – user62198 Aug 30 '15 at 01:35
  • [try a little Google on for size](https://www.google.com/#q=python+format+date) – MattDMo Aug 30 '15 at 01:36

2 Answers2

3

Look at this SO answer. In short, you need to use datetime.strptime() from the datetime module. In your particular case, this should help:

from datetime import datetime
d = datetime.strptime('Feb-15', '%b-%y')

d is of type datetime. You can then use python to compute time differences. This answer provides a possible way of computing time differences between two datetime objects.

Look here for more format options you can use with strptime.

Community
  • 1
  • 1
jorgeh
  • 1,727
  • 20
  • 32
  • 1
    OP's data seems to be month-year not month-day. So `strptime()` format string should be ``%b-%y'`. – mhawke Aug 30 '15 at 01:59
  • Oops, you are right @mhawke. I guess I glossed over that. I've fixed it in the answer. Thanks for catching that! – jorgeh Aug 30 '15 at 02:24
1

The easiest way is to convert your month-year strings to datetime objects, then perform some simple arithmetic:

from datetime import datetime

def elapsed_months(date1, date2=datetime.today()):
    return abs(date1.year * 12 + date1.month) - (date2.year * 12 + date2.month)

>>> dt1 = datetime.strptime('Feb-94', '%b-%y')
>>> elapsed_months(dt1)
>>> elapsed_months
258
>>> elapsed_months(datetime.strptime('Aug-15', '%b-%y'))
0
>>> elapsed_months(datetime.strptime('Aug-15', '%b-%y'), datetime.strptime('Aug-18', '%b-%y'))
36
# order of dates does not matter
>>> elapsed_months(datetime.strptime('Aug-18', '%b-%y'), datetime.strptime('Aug-15', '%b-%y'))
36
mhawke
  • 84,695
  • 9
  • 117
  • 138