1

I have a datetime type and I want to convert it into int but precision in milliseconds. For example I have datetime in UTC 2018-11-19 02:19:53.497 and I want it convert to 1542593993497

Currently the function I wrote is following:

def convert(inputDatetime):
    return int((inputDatetime - datetime.datetime(1970,1,1)).total_seconds())

Here the datetime is precision in millionseconds for example, datetime.datetime(2009, 3, 20, 13, 55, 18, 993000)

The function for now can only convert the datetime to int precision in seconds. How should I make the precision to be in millionseconds?

The Python version I am currently use is 2.7

Terry Zhang
  • 4,541
  • 8
  • 23
  • 29

1 Answers1

1

Grabbed from the accepted answer How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

import datetime

epoch = datetime.datetime.utcfromtimestamp(0)

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

Test:

dt = datetime.datetime(2009, 3, 20, 13, 55, 18, 993000)
print("%d" % unix_time_millis(dt))  # 1237557318993

The key point is that calculating(dt - epoch).total_seconds() should return seconds in floating point format (i.e. milliseconds included), then multiplied by 1000.0.

duong_dajgja
  • 4,196
  • 1
  • 38
  • 65