Finger twist
Finger twist

Reputation: 3786

function vs lambda statement

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 ..

Upvotes: 0

Views: 646

Answers (2)

Winston Ewert
Winston Ewert

Reputation: 45039

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.

Upvotes: 3

srgerg
srgerg

Reputation: 19329

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'

Upvotes: 3

Related Questions