Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python convert long to date

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.

like image 884
Lucas Kauffman Avatar asked May 19 '12 10:05

Lucas Kauffman


2 Answers

time.ctime() gives you the string representation of the time.

it should work with:

datetime.datetime.fromtimestamp(myNumber).strftime('%Y-%m-%d %H:%M:%S')
like image 104
mata Avatar answered Sep 20 '22 12:09

mata


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'
like image 40
Burhan Khalid Avatar answered Sep 20 '22 12:09

Burhan Khalid