Microsoft Tick time to Python Datetime

Question:

There’s a lot of answers to my question but mine is a little different in that I’m not entirely sure if its Microsoft’s tick time. The situation is I’m receiving the following from my firms API and they’ve told me its tick time but it doesn’t match with what I’m getting after using methods from SO to convert.

enter image description here

    import datetime
    TICK_MASK = 4611686018427387903
    _Datetime_nano_hundred_ticks = 5249825230441140085
    print(datetime.datetime(1, 1, 1) + datetime.timedelta(microseconds=TICK_MASK // 100))
    print(datetime.datetime(1, 1, 1) + datetime.timedelta(microseconds=_Datetime_nano_hundred_ticks // 100))

As shown above, the actual time that they’ve converted for me is 2023-03-09 01:13:21 UTC but no idea how to convert given the above provided fields. My question is whether anyone have come across TICKS_MASK or _Datetime_nano_hundred_ticks and if so if they know how to convert it in python. Wonder if its a field from C# im not aware of. (i would ask my devs but thats a looooonnng story) I need to convert because I need higher granularity which supposedly converting will give me. Reasons unknown to me is why it gives me seconds granularity initially.

Asked By: user1234440

||

Answers:

TICK_MASK is a mask, _Datetime_nano_hundred_ticks contains the ticks, one tick represents one ten-millionth of a second.

https://learn.microsoft.com/en-us/dotnet/api/system.datetime.ticks?view=net-7.0

import datetime
TICK_MASK = 4611686018427387903
_Datetime_nano_hundred_ticks = 5249825230441140085

UNIX_EPOCH = 621355968000000000
total_ticks = TICK_MASK & _Datetime_nano_hundred_ticks
timestamp_hundred_nanoseconds = total_ticks - UNIX_EPOCH
timestamp_microseconds = (int)(timestamp_hundred_nanoseconds / 10)
timestamp_seconds = (int)(timestamp_microseconds / 1000000)
microseconds = timestamp_microseconds - timestamp_seconds * 1000000

print(datetime.datetime.fromtimestamp(timestamp_seconds) + 
      datetime.timedelta(microseconds = microseconds))
Answered By: shingo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.