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

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

What about:

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

Im 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 — Im not completely sure.

EDIT

If the %f modifier doesnt 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, Im assuming you just want to truncate the precision.

This solution is very similar to that provided by @gdw2 , only that the string formatting is correctly done to match what you asked for – Should be as compact as possible

>>> import datetime
>>> a = datetime.datetime.now()
>>> %s:%s.%s % (a.minute, a.second, str(a.microsecond)[:2])
31:45.57

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

if you want your datetime.now() precise till the minute , you can use

datetime.strptime(datetime.now().strftime(%Y-%m-%d %H:%M), %Y-%m-%d %H:%M)

similarly for hour it will be

datetime.strptime(datetime.now().strftime(%Y-%m-%d %H), %Y-%m-%d %H)

It is kind of a hack, if someone has a better solution, I am all ears

Leave a Reply

Your email address will not be published.