Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get time in millisecond since epoch in python for a custom time?

Tags:

python

time

epoch

I am trying to get the time in millisecond since epoch passed for a custom time.

I tried using the following code and was able to get the time in seconds since epoch passed.

dt = datetime(2022,5,1,0,0,1,100000)
print(dt)
endtime = time.mktime(dt.timetuple())
endtime = endtime * 1000
print(endtime)

This however, stops at seconds and I get the value of 1651343401000 instead of 1651343401100.

Can someone please help me with it?

like image 618
Gokul Avatar asked Dec 30 '25 06:12

Gokul


1 Answers

You're making it much too hard on yourself. The API already offers what you're looking for:

>>> dt
datetime.datetime(2022, 5, 1, 0, 0, 1, 100000)
>>> 
>>> dt.timestamp()
1651388401.1

Feel free to pick out the integer and fractional parts of that, if you like. Or scale the final component:

>>> millis = dt.microsecond / 1e3
>>> millis
100.0

As a separate matter, you're probably better off steering away from naïve stamps and preferring UTC. Then "seconds since epoch" will have the conventional meaning.

>>> from datetime import timezone
>>> dt = datetime(2022, 5, 1, 0, 0, 1, 100_000, tzinfo=timezone.utc)
>>> dt.timestamp()
1651363201.1
like image 190
J_H Avatar answered Jan 01 '26 20:01

J_H