Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : INPUT a microtime float, RESULT a formatted datetime

I'm so confused with the Python time and datetime methods. Can someone maybe help me?

I just want to achieve a conversion from a microtime Float to a formatted string in this format:

mt = 1342993416.0
start_time_format = '%Y-%m-%d %H:%M:%S'

// Some time or datetime magic here..

OUTPUT >> The file's date is: 2012-07-23 19:00:00

1 Answers

Use the .fromtimestamp() class method:

>>> import datetime
>>> mt = 1342993416.0
>>> datetime.datetime.fromtimestamp(mt)
datetime.datetime(2012, 7, 22, 23, 43, 36)

then use the strftime method to format the output:

>>> start_time_format = '%Y-%m-%d %H:%M:%S'
>>> datetime.datetime.fromtimestamp(mt).strftime(start_time_format)
'2012-07-22 23:43:36'

You can also use the time.strftime function:

>>> import time
>>> time.strftime(start_time_format, time.localtime(mt))
'2012-07-22 23:43:36'
like image 121
Martijn Pieters Avatar answered Jun 26 '26 18:06

Martijn Pieters