6

I am trying to figure out one simple thing - how to convert arrow.Arrow object into milliseconds. I was reading following thread but it still not clear to me how to get a long number in milliseconds.

I want something like:

def get_millis(time: arrow.Arrow):
     ... some magic goes here ...


print(get_millis(time))     
OUTPUT: 
1518129553227 

Thanks

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
Wild Goat
  • 3,509
  • 12
  • 46
  • 87

5 Answers5

6

This is an inelegant answer: from your linked question, you can get the milliseconds as a string and then add them to the timestamp:

import arrow
now = arrow.utcnow()
s = now.timestamp
ms = int(now.format("SSS"))
print(s * 1000 + ms)

Which prints:

1518131043594
import random
  • 3,054
  • 1
  • 17
  • 22
6

Essentially the property you're looking for is

float_timestamp

E.g.

now_millisecs = round(arrow.utcnow().float_timestamp, 3)
now_microsecs = round(arrow.utcnow().float_timestamp, 6)

if you don't like the floating point, you can take it from here with:

str(now_millisecs).replace('.', '')

I personally leave the floating point representation for both visual convenience and ease of calculations (comparisons etc.).

rbrook
  • 81
  • 1
  • 3
  • 2
    If you want an integer number of milliseconds, rather than rounding, converting to a string, removing the decimal point, and converting back to an integer, you can just multiply by 1,000 and then round: `round(arrow.utcnow().float_timestamp * 1000)`. It's simpler, clearer, and slightly faster. – P Daddy Oct 25 '19 at 12:41
  • That said, your answer is absolutely the best one here. – P Daddy Oct 25 '19 at 12:41
3
import arrow


def get_millis(time):
    return time.timestamp * 1000 + time.microsecond / 1000


print(get_millis(arrow.now()))
northtree
  • 8,569
  • 11
  • 61
  • 80
1

You can also format to ms official docs and then parse to int and cut it to the length than you needed.

int(arrow.utcnow().format("x")[:13])
olidroide
  • 113
  • 6
0

Here is a readable way:

import arrow

def get_millis():
    return int(arrow.utcnow().timestamp() * 1000)
Andrew Nodermann
  • 610
  • 8
  • 13