0

Lambda is confusing me a little, here is what I've got :

lmb = lambda d: datetime.datetime.strptime(d["Date[G]"]+"-"+d["Time[G]"], "%d-%b-%Y-%H:%M:%S.%f")

if I write a function like this :

def time(d):
    t = datetime.datetime.strptime(d["Date[G]"]+"-"+d["Time[G]"], "%d-%b-%Y-%H:%M:%S.%f")
    return t.strftime("%d-%b-%Y-%H")

I can return t.strftime("%d-%b-%Y-%H").

Can I embed a somethine like t.strftime("%d-%b-%Y-%H") in my lambda statement ?

EDIT

I`ve tried this :

lmb = lambda d: datetime.datetime.strptime(d["Date[G]"]+"-"+d["Time[G]"], "%d-%b-%Y-%H:%M:%S.%f").strftime("%d-%b-%Y-%H")

but it returns :

AttributeError: 'str' object has no attribute 'strftime'

which doesn't happen using the function ..

2 Answers 2

3

Sure:

lmb = lambda d: datetime.datetime.strptime(d["Date[G]"]+"-"+d["Time[G]"], "%d-%b-%Y-`%H:%M:%S.%f").strftime("%d-%b-%Y-%H")

But it pretty quickly just makes sense to use a function.

Sign up to request clarification or add additional context in comments.

2 Comments

I could use a function but I`m using the lambda statement this way : for k, g in itertools.groupby(csvReader, key = lmb)
@Fingertwist I copied/pasted your new version, and I don't get the error. You can pass the function to groupby, functions and lambda are the exact same thing.
3

Yes, you can do it like this:

lmb = lambda d: datetime.datetime.strptime(d["Date[G]"]+"-"+d["Time[G]"], "%d-%b-%Y-%H:%M:%S.%f").strftime("%d-%b-%Y-%H")

I tested this on Python 2.7:

>>> lmb = lambda d: datetime.datetime.strptime(d["Date[G]"]+"-"+d["Time[G]"], "%d-%b-%Y-%H:%M:%S.%f").strftime("%d-%b-%Y-%H")
>>> lmb({"Date[G]": "22-Apr-2012", "Time[G]": "07:23:24.123"})
'22-Apr-2012-07'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.