Search code examples
pythondatetimepython-datetime

Count of days of each month from a list of dates python


How can I count the number of days of each month for current year from a list of dates in python. Consider I have a date list as:

10/Mar/2016 06:39:31
16/Nov/2015 06:16:27
16/Dec/2012 06:39:31
16/Dec/2015 06:16:27
9/Mar/2016 06:16:27
15/Nov/2015 06:16:27
15/Mar/2012 06:39:31
15/Nov/2015 06:16:27
15/Sep/2015 06:16:27
15/Jan/2015 06:16:27
16/Feb/2016 06:16:27
16/Jan/2016 06:39:31
16/Feb/2016 06:39:31
15/Feb/2012 06:16:27
12/Mar/2016 06:16:27
16/Nov/2012 06:16:27
8/Jan/2016 06:16:27
10/Mar/2016 06:39:31
16/Nov/2012 06:39:31
16/Nov/2012 06:16:20
7/Mar/2016 06:16:27
15/Nov/2012 06:16:27
16/Jan/2016 06:16:27
16/Oct/2015 06:39:31

Now I want Jan-3 , Feb-2, Mar-5 and so on.

I tried

from datetime import datetime as date_for_conv
if(times> date_for_conv.strptime(times, "%d/%b/%Y %H:%M:%S").strftime("2016/Jan/%d")):
    jan+=1

times is the list element iterated in a loop. This gives the count for Jan month only, I want to do it in a single condition check. What should I do?


Solution

  • A simple way to count is to use a dictionary. Add new keys and increment if it exists:

    from datetime import datetime
    times = ['10/Mar/2016 06:39:31','16/Nov/2015 06:16:27','16/Dec/2012 06:39:31','16/Dec/2015 06:16:27',
             '9/Mar/2016 06:16:27','15/Nov/2015 06:16:27','15/Mar/2012 06:39:31','15/Nov/2015 06:16:27',
             '15/Sep/2015 06:16:27','15/Jan/2015 06:16:27','16/Feb/2016 06:16:27','16/Jan/2016 06:39:31',
             '16/Feb/2016 06:39:31','15/Feb/2012 06:16:27','12/Mar/2016 06:16:27','16/Nov/2012 06:16:27',
             '8/Jan/2016 06:16:27','10/Mar/2016 06:39:31','16/Nov/2012 06:39:31','16/Nov/2012 06:16:20',
             '7/Mar/2016 06:16:27','15/Nov/2012 06:16:27','16/Jan/2016 06:16:27','16/Oct/2015 06:39:31']
    
    counters = {}
    for t in times:
        month = datetime.strptime(t, "%d/%b/%Y %H:%M:%S").strftime('%b')
        if month in counters:
            counters[month] += 1
        else:
            counters[month] = 1
    
    for k,v in counters.items():
        print('{}-{}'.format(k,v))
    

    This returns:

    Oct-1
    Dec-2
    Mar-6
    Jan-4
    Feb-3
    Sep-1
    Nov-7