Newbie question, list comprehension

Larry Bates larry.bates at websafe.com`
Sat Jun 7 15:46:17 EDT 2008


Johannes Bauer wrote:
> Hello group,
> 
> I'm currently doing something like this:
> 
> import time
> localtime = time.localtime(1234567890)
> fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % (localtime[0], localtime[1], 
> localtime[2], localtime[3], localtime[4], localtime[5])
> print fmttime
> 
> For the third line there is, I suppose, some awesome python magic I 
> could use with list comprehensions. I tried:
> 
> fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in 
> range(0, 5)])
> 
> But that didn't work:
> 
> Traceback (most recent call last):
>   File "./test.py", line 8, in ?
>     fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in 
> range(0, 5)])
> TypeError: int argument required
> 
> As it appearently passed the while list [2009, 02, 14, 0, 31, 30] as the 
> first parameter which is supposed to be substituted by "%04d". Is there 
> some other way of doing it?
> 
> Thanks a lot,
> Regards,
> Johannes
> 
You should look at time.strftime.  It will do the formatting for you so you 
don't have to do it manually as you have.

-Larry



More information about the Python-list mailing list