>>> 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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With