Alex Rivera | Logout

Python convert long to date

Asked 2012-05-19T10:38:35.847
10

I'm trying to convert a long to a date:

class timeStamp(object):
     def getDateTime(self,longDate):                                                                                                                                 
         myNumber = float(longDate)
         return str(datetime.datetime.fromtimestamp(time.ctime(myNumber)).strftime('%Y-%m-%d %H:%M:%S'))

But I have a weird error:

 File "./index.py", line 104, in getDateTime
    return str(datetime.datetime.fromtimestamp(time.ctime(myNumber)).strftime('%Y-%m-%d %H:%M:%S'))
TypeError: a float is required

Why is it complaining when I explicitly cast it to float? The long is a Unix timestamp stored as a long in mysql.

Edit
Report

1 Answer

12

What you need is simply datetime.datetime.fromtimestamp(myNumber).strftime('%Y-%m-%d %H:%M:%S') as time.ctime() returns a string:

>>> time.ctime()
'Sat May 19 13:46:09 2012'
answered 2012-05-19T10:50:47.957

Your Answer