Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime: Round/trim number of digits in microseconds

Currently I am logging stuff and I am using my own formatter with a custom formatTime():

def formatTime(self, _record, _datefmt):     t = datetime.datetime.now()     return t.strftime('%Y-%m-%d %H:%M:%S.%f') 

My issue is that the microseconds, %f, are six digits. Is there anyway to spit out less digits, like the first three digits of the microseconds?

like image 590
Parham Avatar asked Jun 14 '12 19:06

Parham


People also ask

How many digits are in a microsecond?

A microsecond is an SI unit of time equal to one millionth (0.000001 or 10−6 or 1⁄1,000,000) of a second. Its symbol is μs, sometimes simplified to us when Unicode is not available.

How do you round milliseconds Python?

Python Pandas - How to Round the DateTimeIndex with milliseconds frequency. To round the DateTimeIndex with milliseconds frequency, use the DateTimeIndex. round() method. For milliseconds frequency, use the freq parameter with value 'ms'.

How do I get milliseconds from datetime?

To display the millisecond component of a DateTime valueParse(String) or DateTimeOffset. Parse(String) method. To extract the string representation of a time's millisecond component, call the date and time value's DateTime.

How to round microseconds in a date?

Basically you do manual rounding on the date object itself first, then you can safely trim the microseconds. Show activity on this post. Edit: As some pointed out in the comments below, the rounding of this solution (and the one above) introduces problems when the microsecond value reaches 999500, as 999.5 is rounded to 1000 (overflow).

How to round the datetime to the nearest value?

This optional parameter specifies how to round the DateTime. The default rounding method is '='. You can change the method by using the following options: '=' rounds up or down to the nearest value (default). Values of 5 or greater are rounded up. Values less than 5 are rounded down. The rounded result.

How to get milliseconds from a datetime?

The solution I ended up using to get milliseconds was to use the microsecond attribute of the datetime object, divide it by 1000.0, pad it with zeros if necessary, and round it with format. It looks like this: Show activity on this post. You can subtract the current datetime from the microseconds. Show activity on this post.

How do I round the hour and date parts of a datetime?

The Regional and Language Options in Windows affect how the hour and date parts of a DateTime are rounded. To display a DateTime in a specific format, we recommend that you use the Format method instead of the RoundDateTime method. This example shows how to use the RoundDateTime method to round to the nearest second.


2 Answers

The simplest way would be to use slicing to just chop off the last three digits of the microseconds:

def format_time():     t = datetime.datetime.now()     s = t.strftime('%Y-%m-%d %H:%M:%S.%f')     return s[:-3] 

I strongly recommend just chopping. I once wrote some logging code that rounded the timestamps rather than chopping, and I found it actually kind of confusing when the rounding changed the last digit. There was timed code that stopped running at a certain timestamp yet there were log events with that timestamp due to the rounding. Simpler and more predictable to just chop.

If you want to actually round the number rather than just chopping, it's a little more work but not horrible:

def format_time():     t = datetime.datetime.now()     s = t.strftime('%Y-%m-%d %H:%M:%S.%f')     head = s[:-7] # everything up to the '.'     tail = s[-7:] # the '.' and the 6 digits after it     f = float(tail)     temp = "{:.03f}".format(f)  # for Python 2.x: temp = "%.3f" % f     new_tail = temp[1:] # temp[0] is always '0'; get rid of it     return head + new_tail 

Obviously you can simplify the above with fewer variables; I just wanted it to be very easy to follow.

like image 70
steveha Avatar answered Oct 02 '22 10:10

steveha


As of Python 3.6 the language has this feature built in:

def format_time():     t = datetime.datetime.now()     s = t.isoformat(timespec='milliseconds')     return s 
like image 41
Rob Avatar answered Oct 02 '22 10:10

Rob