Reputation: 23587
I am given timestamps in binary format example:
5249363694976427904
How can I convert this to unix timestamp in Python?
I was pointed to the following website about the format but its in C#: here
The following link is the function in c# that is used to generate this binary date time in c#: here
Upvotes: 0
Views: 644
Reputation: 781
The int
is a representation of a set of 2-bit and 62-bit values, the first being the Kind
of timestamp (UTC, local, undefined). The second is the number of ticks since 0001-01-01 00:00:00, where each tick is defined as 0.1 microseconds.
So we just need to convert the int
back to binary, split it into each part, convert to microseconds and then add a timedelta
to our base date.
This should do it for you:
from datetime import datetime, timedelta
def ticks_to_datetime(binary_time: int) -> datetime:
binary_time_string = f"{binary_time:064b}"
# Not used here, but you can expand to check based on
# https://learn.microsoft.com/en-us/dotnet/api/system.datetimekind?view=net-5.0
time_kind = binary_time_string[:2]
time_microseconds = int(binary_time_string[2:], 2) / 10
time_difference = timedelta(microseconds=time_microseconds)
return datetime(1, 1, 1) + time_difference
my_time = ticks_to_datetime(5249363694976427904)
print(f"{my_time} | {my_time.timestamp()}")
Result:
2021-09-20 20:47:34.904000 | 1632170854.904
[Finished in 68ms]
Note that I'm not handling the Kind
of the binary time, so if you find yourself needing to deal with timestamps from local timezones, you'll need to modify the datetime
on the return
line to take this into account.
Upvotes: 3