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

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
user1234440
  • 22,521
  • 18
  • 61
  • 103
  • 1
    Does this answer your question? [convert 64 bit windows date time in python](https://stackoverflow.com/questions/4869769/convert-64-bit-windows-date-time-in-python) – mkrieger1 Oct 08 '21 at 18:36
  • Could you please provide more explanations? the given number is not even binary! A binary number contains ones and zeros only. – Mohammad Jafari Oct 08 '21 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. – Michael Butscher Oct 08 '21 at 18:44
  • i dont think the suggested answer solves my problem – user1234440 Oct 12 '21 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: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tobinary?view=net-5.0 – user1234440 Oct 12 '21 at 14:31

1 Answers1

3

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Da Chucky
  • 781
  • 3
  • 13