0

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

5
  • 1
    Does this answer your question? convert 64 bit windows date time in python Commented Oct 8, 2021 at 18:36
  • Could you please provide more explanations? the given number is not even binary! A binary number contains ones and zeros only. Commented Oct 8, 2021 at 18:39
  • @mkrieger1 It isn't the same as it contains according to the link a 2bit field to mark timestamp as local, UTC or unspecified. Moreover its epoch is year 1 of the Gregorian calendar. Commented Oct 8, 2021 at 18:44
  • i dont think the suggested answer solves my problem Commented Oct 12, 2021 at 14:13
  • that is a different format then mine, please see the following link which is the function used in c# to convert to the binary representation: learn.microsoft.com/en-us/dotnet/api/… Commented Oct 12, 2021 at 14:31

1 Answer 1

3
+50

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.