How to Convert a Datetime Object to Milliseconds Since Epoch (Unix Time) in Python

Converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000) # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

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

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 convert datetime object to time_ns

Since python 3.3 datetime has a timestamp function. Make sure to replace the timezone, otherwise local timezone will being taken and if you want to have nanosecond number you can multiply the seconds number.

from datetime import datetime; 
print(datetime(2022,2,22,15,41,50).replace(tzinfo=timezone.utc).timestamp()*10**9)

datetime to Unix timestamp with millisecond precision

Datetime objects have a field named microsecond. So one way to achieve what you need is:

time.mktime(then.timetuple())*1e3 + then.microsecond/1e3

This returns milliseconds since UNIX epoch with the required precision.

Is there a way i can use datetime to convert a string to milliseconds without using timedelta?

Since timestamps are relative to the Unix Epoch (1970-01-01) you can make a datetime object from your time by prepending that date to it and then getting the timestamp of the resultant object to get the time string converted to seconds . Since python timestamps are floating point representations of seconds since the epoch, you will need to multiply by 1000 and convert to integer to get the number of milliseconds:

from datetime import datetime

t = "00:05:52.654321"
d = datetime.strptime('1970-01-01 ' + t, '%Y-%m-%d %H:%M:%S.%f')
print(int(d.timestamp()*1000))

Output:

352654

If you actually want microseconds, multiply by 1000000 instead.

As an alternative, you can split the time string on : and sum the parts, multiplying by 60 or 3600 to convert the hour and minute parts to seconds:

t = "00:05:52.654321"

millisecs = int(sum([float(v) * 1000 * 60 ** (2 - i) for i, v in enumerate(t.split(':'))]))
print(millisecs)

Output:

352654

Again, if you want microseconds, just multiply by 1000000 instead of 1000.

Convert date in words to epoch time stamp in python

With the input from the comment you could try:

from datetime import datetime

dates = {'Date': ['May 01, 2022', 'Apr 30, 2022', 'Apr 29, 2022', 'Apr 28, 2022', 'Apr 27, 2022']}
dates['Date'] = [
datetime.strptime(date, "%b %d, %Y").timestamp() for date in dates['Date']
]


Related Topics



Leave a reply



Submit