Search code examples
pythonpython-3.xdatetimeunix-timestamp

Convert datetime object into milliseconds


This has probably been asked like a million times, but I still didn't manage to do it.

The case is, that I need to calculate the time between two unix timestamps:

eg: 1494708797619 - 1494709197066

What I have so far:

from datetime import datetime
a = datetime.fromtimestamp(1494708797619/1000.0)
b = datetime.fromtimestamp(1494709197066/1000.0)
c = b-a
print(c)

But the answer is currently in datetime format like that:

0:06:39.447000

But I'd like it to be something like that:

399447000

Cheers!


Solution

  • from datetime import datetime
    a = datetime.fromtimestamp(1494708797619/1000.0)
    b = datetime.fromtimestamp(1494709197066/1000.0)
    c = int((b-a).total_seconds() * 1000)
    print(c)
    

    Will output

    399447
    

    But shortest way will be 1494708797619 - 1494709197066 as Daniel noted