How to use milliseconds instead of microsenconds in datetime python

Viewed 672

A client has specified that they use DateTime to store their dates using the format 2021-06-22T11:17:09.465Z, and so far I've been able only to obtain it in string dates, because If I want to maintain the milliseconds it saves them like 2021-06-22T11:17:09.465000.

Is there any possible way to force DateTime to use milliseconds instead of microseconds? I'm aware of the %f for microseconds in the format, but I've tried everything I can think of to reduce those 3 decimals while keeping it DateTime with no results however.

Thanks.

4 Answers

Something like this works:

from datetime import datetime
dt = datetime.now()
print(f"{dt:%Y/%m/%dT%H:%M:%S}.{f'{dt:%f}'[:3]}")

Hope I help.

I assume you're looking for this? See also my general comment at question.

The variable 3 in [:3] can be adjusted to your liking for amount of zeros in ms to ns range. Use the type() to show you its a DateTime object.

import time
from datetime import datetime

tm = time.time()

print(tm)

dt = str(tm).split('.')

print(dt)

timestamp = float(dt[0] + '.' + dt[1][:3]) 

dt_object = datetime.fromtimestamp(timestamp)

print(dt_object)

This prints for example:

tm : 1638463260.919723

dt : ['1638463260', '919723']

and

dd_object : 2021-12-02 17:41:00.919000

You can divide nanoseconds by 1000000000 to get seconds and by 1000000 to get milliseconds.

Here is some code that will get nanoseconds:

tim = time.time_ns()

You can then combine the output of this with the rest of the format. Probably not the cleanest solution but it should work.

Related