0

How can I format this date.time variable to include on milliseconds up to 2dp?

Using the date.time module in Python, I have created 2 variables. These are as follows:

begin = datetime.datetime.now()
end = datetime.datetime.now()

I then print the variable below.

time_taken = end - begin

Printing this variable time_taken in this format 0:00:16.664335.

The question I want to ask, is there a simple way to round the milliseconds to 2dp?

I have searched other methods but they seem over-complicated and not worth using.

martineau
  • 119,623
  • 25
  • 170
  • 301

3 Answers3

0

yes the simple way to round a variable:

{selected variable} = round({selected variable}, {number of dp})`

example:

time = 1.3454

time = round(time, 2)

print time 

{out put is 1.35} Hopes this helps.

Aidan
  • 42
  • 6
  • thanks but I tried this method before posting it doesn't work for timedelta objects – Tarun Kang Jul 03 '21 at 16:12
  • This is a way to round off a specific decimal, the timestamp has to be reformatted before rounding off the milliseconds. – fatiu Jul 12 '21 at 11:50
0

Subtracting datetime objects return a timedelta object. It has time upto microseconds stored inside it.

You can get that value & round it to however many points of precision you require.

import time
from datetime import datetime

begin = datetime.now()
time.sleep(0.005)  # 5 ms
end = datetime.now()

time_taken = end - begin  # this is a timedelta object

time_taken_ms = round(time_taken.total_seconds() * 1000, 2)

print(time_taken_ms)

Output:

6.97
rdas
  • 20,604
  • 6
  • 33
  • 46
0

The result of subtracting two datetimes is a timedelta object which only stores days, seconds, and microseconds internally and that is what is normally displayed when you print their values. If you desire something different, you will need to define your own formatting function. Below is and example of one that does what you want with respect to milliseconds:

import datetime
import time


def format_timedelta(td):
    """ Format a timedelta into this format D:H:M:SS.ss """
    days = td.days
    hours, remainder = divmod(td.seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    seconds += td.microseconds / 1e6
    return (f'{days}:{hours}:{minutes}:{seconds:02.2f}' if days else
                   f'{hours}:{minutes}:{seconds:02.2f}')


begin = datetime.datetime.now()
time.sleep(0.123)  # 123 ms
end = datetime.datetime.now()

time_taken = end - begin
print(format_timedelta(time_taken))  # -> 0:0:0.12

martineau
  • 119,623
  • 25
  • 170
  • 301