How to Get the Current Time in Milliseconds in Python

How do I get the current time in milliseconds in Python?

Using time.time():

import time

def current_milli_time():
return round(time.time() * 1000)

Then:

>>> current_milli_time()
1378761833768

Convert python datetime to timestamp in milliseconds

In Python 3 this can be done in 2 steps:

  1. Convert timestring to datetime object
  2. Multiply the timestamp of the datetime object by 1000 to convert it to milliseconds.

For example like this:

from datetime import datetime

dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
'%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000

print(millisec)

Output:

1482223122760.0

strptime accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime object. The format string (second argument) specifies the actual format of the string that you have passed.

Here is the explanation of the format specifiers from the official documentation:

  • %d - Day of the month as a zero-padded decimal number.
  • %m - Month as a zero-padded decimal number.
  • %Y - Year with century as a decimal number
  • %H - Hour (24-hour clock) as a zero-padded decimal number.
  • %M - Minute as a zero-padded decimal number.
  • %S - Second as a zero-padded decimal number.
  • %f - Microsecond as a decimal number, zero-padded to 6 digits.

How to get time in millisecond since epoch in python for a custom time?

You're making it much too hard on yourself.
The API already offers what you're looking for:

>>> dt
datetime.datetime(2022, 5, 1, 0, 0, 1, 100000)
>>>
>>> dt.timestamp()
1651388401.1

Feel free to pick out the integer and fractional parts of that, if you like.
Or scale the final component:

>>> millis = dt.microsecond / 1e3
>>> millis
100.0

As a separate matter,
you're probably better off
steering away from naïve stamps and preferring UTC.
Then "seconds since epoch" will have the conventional meaning.

>>> from datetime import timezone
>>> dt = datetime(2022, 5, 1, 0, 0, 1, 100_000, tzinfo=timezone.utc)
>>> dt.timestamp()
1651363201.1

How do I create a datetime in Python from milliseconds?

Just convert it to timestamp

datetime.datetime.fromtimestamp(ms/1000.0)

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

It appears to me that the simplest way to do this is

import datetime

epoch = datetime.datetime.utcfromtimestamp(0)

def unix_time_millis(dt):
return (dt - epoch).total_seconds() * 1000.0

Python current timestamp for UTC with millisecond accuracy

Here's one way of getting milliseconds

ts =  datetime.utcnow()
print ts.microsecond #prints microseconds
print time.mktime(ts.timetuple()) + ts.microsecond * 1e-6

output

128852
1409151725.13

Python speed testing - Time Difference - milliseconds

datetime.timedelta is just the difference between two datetimes ... so it's like a period of time, in days / seconds / microseconds

>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a

>>> c
datetime.timedelta(0, 4, 316543)
>>> c.days
0
>>> c.seconds
4
>>> c.microseconds
316543

Be aware that c.microseconds only returns the microseconds portion of the timedelta! For timing purposes always use c.total_seconds().

You can do all sorts of maths with datetime.timedelta, eg:

>>> c / 10
datetime.timedelta(0, 0, 431654)

It might be more useful to look at CPU time instead of wallclock time though ... that's operating system dependant though ... under Unix-like systems, check out the 'time' command.

How to get the millisecond part while converting to date time from epoch using python

Use datetime.datetime.fromtimestamp

epoch_time = 1571205166751

dt = datetime.datetime.fromtimestamp(epoch_time/1000)

dt.strftime("%Y-%m-%d %H:%M:%S.%f %p")

output:

'2019-10-16 11:22:46.751000 AM'

Note:

%f is not supported in time.strftime

How to get current time in microseconds resolution?

You can print a datetime in that format just by using strftime:

>>> import datetime

>>> now = datetime.datetime.now()

>>> now
datetime.datetime(2019, 10, 17, 12, 45, 58, 294795)

>>> now.strftime("%Y-%m-%dT%H:%M:%S.%f")
'2019-10-17T12:45:58.294795'

Note that this is a separate issue to the resolution of your clock, it may be less than a microsecond. You can check that as well by using:

>>> str(datetime.time.resolution)
'0:00:00.000001'

As per the output, my Linux box (and Python 3.7 on my Win10 box) has a one-microsecond resolution.

Format a datetime into a string with milliseconds

To get a date string with milliseconds, use [:-3] to trim the last three digits of %f (microseconds):

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
'2022-09-24 10:18:32.926'

Or slightly shorter:

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%F %T.%f')[:-3]


Related Topics



Leave a reply



Submit