CuriousDog
CuriousDog

Reputation: 35

Trying to make a list of dates into date.year, date.month, date.day for comparrison?

I have a list of lists, with integer values in each list, that represent dates over an 8 year period.

     dates = [[2014, 11, 14], [2014, 11, 13], ....., [2013, 12, 01].....]

I need to compare these dates so that I can find an average cost per month, with other data stored in the file. So i need to figure out how to iterate through the dates and stop when the month changes. Each date has corresponding cost and volume values that I will need to find the average.

So I was trying to find a way to make the dates in x.year, x.month, x.day format and do it that way but I'm new to python and very confused.

How do I iterate through all of the dates for the 8 year period, but stopping and calculating the average of the data for each particular month and store that average for each month??

Thanks in advance, hope this makes sense.

Upvotes: 2

Views: 84

Answers (2)

Kasravnd
Kasravnd

Reputation: 107357

You can use a dictionary to preserve the year and month as the key and the relative days in a list as value, then you can do any progress on your items which are categorized by the year and month.

>>> dates = [['2014', '11', '14'], ['2014', '10', '13'], ['2014', '10', '01'], ['2014', '12', '01'], ['2013', '12', '01'], ['2013', '12', '09'], ['2013', '10', '01'], ['2013', '10', '05'], ['2013', '04', '01']]
>>> my_dict = {}
>>> 
>>> for y,m,d in dates:
...     my_dict.setdefault((y,m),[]).append(d)
... 
>>> my_dict
{('2013', '10'): ['01', '05'], ('2013', '12'): ['01', '09'], ('2014', '11'): ['14'], ('2014', '10'): ['13', '01'], ('2014', '12'): ['01'], ('2013', '04'): ['01']}
>>> 

You can use a nested list comprehension to convert the result to a nested list of relative month of datetime objects :

>>> [[datetime(int(y),int(m),int(d)) for d in days] for (y,m),days in my_dict.items()]
[[datetime.datetime(2013, 10, 1, 0, 0), datetime.datetime(2013, 10, 5, 0, 0)], [datetime.datetime(2013, 12, 1, 0, 0), datetime.datetime(2013, 12, 9, 0, 0)], [datetime.datetime(2014, 11, 14, 0, 0)], [datetime.datetime(2014, 10, 13, 0, 0), datetime.datetime(2014, 10, 1, 0, 0)], [datetime.datetime(2014, 12, 1, 0, 0)], [datetime.datetime(2013, 4, 1, 0, 0)]]

Upvotes: 3

Erwan Vasseure
Erwan Vasseure

Reputation: 36

If you want to iterate thought you dates array, and do an action every time the month changes you could use this method:

dates = [[2014, 11, 14], [2014, 11, 13], [2013, 12, 1]]
old_m = ""
for year, month, day in dates:
    if old_m != month:
        # calculate average here
        old_m = month

Upvotes: 1

Related Questions