Home > Software design >  How to use milliseconds instead of microsenconds in datetime python
How to use milliseconds instead of microsenconds in datetime python

Time:12-03

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.

CodePudding user response:

I suggest to use the timespec parameter, as described in python docs https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat:

>>> from datetime import datetime
>>> datetime.now().isoformat(timespec='minutes')   
'2002-12-25T00:00'
>>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
>>> datetime.now().isoformat(timespec='milliseconds')
'2021-12-02T14:03:57.937'

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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
  • Related