views:

269

answers:

4

Hi Everybody,

From MySQL query I get data which I put into a dictionary "d":

d = {0: (datetime.timedelta(0, 25200),), 1: (datetime.timedelta(0, 25500),), 2: (datetime.timedelta(0, 25800),), 3: (datetime.timedelta(0, 26100),), 4: (datetime.timedelta(0, 26400),), 5: (datetime.timedelta(0, 26700),)}

I have a list "m" with numbers like:

m = [3, 4, 1, 4, 7, 4]

I'd like to test "m" and if there is number "4", I'd like to receive another list "h" with hours from "d" where index from list "m" would be corresponding with keys from dictionary "d", so: m[1], m[3], m[5] would get me hours assigned to d[1], d[3], d[5] in list "h":

h = [7:05:00, 7:15:00, 7:25:00]

I'll appreciate your input for that...

A: 

Are you asking for

def hms( td ):
    h = dt.seconds // 3600
    m = dt.seconds%3600 // 60
    s = dt.seconds%60
    return h+td.days*24, m, s


[ hms(d[ m[i] ]) for i in m ]

?

S.Lott
+2  A: 

I'm not entirely sure if this is what you're looking for, but I'll take a shot:

>>> indices = [index for index, i in enumerate(m) if i == 4]
>>> h = [d[i][0] for i in indices]

Then you have to process the timedeltas as you want to.

sykora
Thank You for quick and acuarate response!
A: 
deltas = [str(d[i][0]) for i, j in enumerate(m) if j == 4]

produces list of delta representation as strings.

SilentGhost
A: 

So at each index is an n-tuple of timedeltas right? Assuming, from the code, that potentially there could be more than one timedelta at each index. import datetime

import datetime

d = {0: (datetime.timedelta(0, 25200),), 1: (datetime.timedelta(0, 25500),), 2: (datetime.timedelta(0, 25800),), 3: (datetime.timedelta(0, 26100),), 4: (datetime.timedelta(0, 26400),), 5: (datetime.timedelta(0, 26700),)}
m = [3, 4, 1, 4, 7, 4]

def something(m, d):
  h = {}
  for index in m:
    if index in d and index not in h:
      for dt in d[index]:
        total = sum([dt.seconds for dt in d[index]])
        hours = total / 3600
        minutes = (total - (3600 * hours)) / 60
        seconds = (total - (3600 * hours) - (60 * minutes))
        h[index] = "%d:%02d:%02d" % (hours, minutes, seconds)
  return h.values()

print something(m, d) # returns exactly what you asked for
Jesse Dhillon