0
>>> M1
['month:12;year:2006', 'month:7;year:2010']
>>> M2
['month:5;year:2006', 'month:3;year:2010']
>>> M3
['year:2006'; 'month:4;year:2010']

I have 3 list item M1, M2, M3

M1[0] is the Start date 
M2[0] is the End date

is it possible to convert the list this way and perform computations

M1 = 12/2006, 7/2010
M2 = 5/2006, 3/2010
M3 = 0/2006, 4/2010

What i want is to calculate the difference between them in months like,

M1Diff = 43 months
M2Diff =  52 months
M3Diff = 51 months
Ahsan Khan
  • 21
  • 6
  • 5
    It is surely possible. What did you try? – Ashwini Chaudhary Jul 04 '17 at 06:36
  • 1
    How month can be 0? I mean what is the 0th month? – Ahsanul Haque Jul 04 '17 at 06:41
  • @AhsanulHaque , It could make sense that 0 - January, 11 - December. But, He has already 12 which is weird :P – omri_saadon Jul 04 '17 at 06:44
  • Do you actually have strings in the form `'month:12;year:2006'`? Not dictionaries? Do you mean to say that `M1[1]` is the end date, rather than `M2[0]`? Have you tried googling "python convert string to date" and "python get difference between dates"? Do you understand that you're asking two questions which could be asked and tackled separately? – Alex Hall Jul 04 '17 at 06:46
  • I added 0 to be easy ini calculation Obviously i would be doing for anything thats against the forward slassh t1 = (2010-2006)*12 for anythng thats before the forward slash t2 = (4-0) and then adding t = t1+t2 – Ahsan Khan Jul 04 '17 at 06:53
  • @AlexHall Thanks buddy i didn't know python had the built in functions for date also, using import datetime Its really handy Thanks buddy I'm new to python. Python is love. – Ahsan Khan Jul 04 '17 at 06:56
  • Can you please explain how `M2Diff` is `52` and `M3Diff` is `51`. To me, they should be 46 and 52 . – Ahsanul Haque Jul 04 '17 at 06:56
  • 1
    Always google everything. You will be surprised at how often you get results. – Alex Hall Jul 04 '17 at 06:57
  • It is very similar to this one I guess: https://stackoverflow.com/questions/4039879/best-way-to-find-the-months-between-two-dates – BData Jul 04 '17 at 07:00

1 Answers1

1

I will show how to do it, for the first, in same way you can implement

def diff_month(d1, d2):
    return abs((d1.year - d2.year) * 12 + d1.month - d2.month)


M1=['month:12;year:2006', 'month:7;year:2010']
d1 = datetime.strptime(M1[0], 'month:%m;year:%Y')
d2 = datetime.strptime(M1[1], 'month:%m;year:%Y')

diff_month(d1, d2)

In this method just use for loop for all the date collection.

Hope this helps

Prags
  • 811
  • 5
  • 17