pythondatetimetime

How to get min, seconds and milliseconds from datetime.now() in python?


>>> a = str(datetime.now())
>>> a
'2012-03-22 11:16:11.343000'

I need to get a string like that: '16:11.34'.

Should be as compact as possible.

Or should I use time() instead? How do I get it?


Solution

  • What about:

    datetime.now().strftime('%M:%S.%f')[:-4]

    I'm not sure what you mean by "Milliseconds only 2 digits", but this should keep it to 2 decimal places. There may be a more elegant way by manipulating the strftime format string to cut down on the precision as well -- I'm not completely sure.

    EDIT

    If the %f modifier doesn't work for you, you can try something like:

    now=datetime.now()
    string_i_want=('%02d:%02d.%d'%(now.minute,now.second,now.microsecond))[:-4]
    

    Again, I'm assuming you just want to truncate the precision.