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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With