Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 697
Prostak Avatar asked Mar 22 '12 18:03

Prostak


People also ask

How can I get seconds in datetime?

Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch. Use the timestamp() method. If your Python version is greater than 3.3 then another way is to use the timestamp() method of a datetime class to convert datetime to seconds.

How do you use now 2 in Python?

Get Current Time in PythonUse the time. time() function to get the current time in seconds since the epoch as a floating-point number. This method returns the current timestamp in a floating-point number that represents the number of seconds since Jan 1, 1970, 00:00:00. It returns the current time in seconds.

What is datetime datetime now () in Python?

Python library defines a function that can be primarily used to get current time and date. now() function Return the current local date and time, which is defined under datetime module. Parameters : tz : Specified time zone of which current time and date is required.


1 Answers

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.

like image 164
mgilson Avatar answered Sep 19 '22 15:09

mgilson