Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Arrow milliseconds

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

like image 403
Wild Goat Avatar asked Feb 08 '18 22:02

Wild Goat


People also ask

How do I show milliseconds in Python?

strptime() function in python converts the string into DateTime objects. The strptime() is a class method that takes two arguments : string that should be converted to datetime object.

How do you use arrow modules in Python?

Arrow is a Python module for working with date and time. It offers a sensible and human-friendly approach to creating, manipulating, formatting and converting dates, times and timestamps. It allows easy creation of date and time instances with timezone awareness.


2 Answers

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
like image 148
import random Avatar answered Oct 10 '22 08:10

import random


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.).

like image 42
rbrook Avatar answered Oct 10 '22 08:10

rbrook