not2qubit
not2qubit

Reputation: 17037

How can I truncate milliseconds to 2 most significant decimals in strftime()

I have a datetime object that is printed with:

from datetime import datetime

ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f").strip()
print('TS: {}'.format(ts))

# "2020-12-03 02:13:27.823467"

However, I only want the first 2 digits of the milliseconds to be shown, like this: 2020-12-03 02:13:27.82. Using "%.2f" didn't work, and perhaps there's another time function more suitable?

What is the best way to do this without introducing (possibly laggy) regex string manipulations?

Upvotes: 0

Views: 1809

Answers (2)

norok2
norok2

Reputation: 26916

What about something like the following?

import datetime


now = datetime.datetime.now()
ts = now.strftime('%Y-%m-%d %H:%M:%S') + '.{:02d}'.format(round(now.microsecond, -4))[:3]
print('TS: {}'.format(ts))
# TS: 2020-12-03 01:22:01.86

EDIT

Perhaps a better parametrized solution would be:

import datetime


def largest_digits(value, num_digits=2, max_digits=6):
    discard_digits = num_digits - max_digits 
    base = 10 ** -discard_digits
    return f'{round(value, discard_digits) // base:02d}'


now = datetime.datetime.now()
ts = now.strftime('%Y-%m-%d %H:%M:%S') + '.' + largest_digits(now.microsecond, 2)
print('TS: {}'.format(ts))
# TS: 2020-12-03 01:22:01.86

Upvotes: 1

not2qubit
not2qubit

Reputation: 17037

Aaahi, the answer was trivial! Use string selection.

ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f").strip()[:-4]

Upvotes: 0

Related Questions