3

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
mskfisher
  • 3,291
  • 4
  • 35
  • 48

1 Answers1

8

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'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Yep, that did the trick. I'm sorry for the stupidity, but sometimes I can make such complex stuff, and sometimes and can't even manage to get the minor things to work.. Silly me :P. Thank you good sir :) –  Jul 24 '12 at 21:20
  • For the curious, here's a question that explains some of the differences between datetime and time: http://stackoverflow.com/questions/7479777/difference-between-datetime-vs-time-modules – Lenna Jul 24 '12 at 21:20
  • Thank you Lenna, I will surely look into that for future projects :) –  Jul 24 '12 at 21:23