如何解析含超长格式时间戳的日志并转换为1970-01-01以来的毫秒数?
Convert .NET DateTime Ticks to Unix Epoch Milliseconds
Hey there! That long timestamp you're working with (636597250599883050, 636597142599883050) is .NET DateTime Ticks—a format that counts 100-nanosecond intervals starting from January 1, 0001 (UTC). Here's a straightforward way to convert it to milliseconds since the Unix epoch (January 1, 1970):
Step-by-Step Explanation
- Use the fixed epoch offset: The number of ticks between the .NET epoch (0001-01-01 UTC) and the Unix epoch (1970-01-01 UTC) is a constant:
621355968000000000. - Calculate ticks since Unix epoch: Subtract this fixed offset from your target tick value.
- Convert to milliseconds: Since 1 tick = 100 nanoseconds, divide the result by
10000(because 1 millisecond = 1,000,000 nanoseconds = 10,000 ticks).
Example Code (Python)
def ticks_to_unix_ms(ticks): # Fixed ticks between .NET epoch (0001-01-01) and Unix epoch (1970-01-01) net_to_unix_ticks = 621355968000000000 # Convert to milliseconds since Unix epoch return (ticks - net_to_unix_ticks) // 10000 # Test with your sample timestamps local_time_ticks = 636597250599883050 utc_time_ticks = 636597142599883050 print(ticks_to_unix_ms(local_time_ticks)) # Output: 1525197459988 print(ticks_to_unix_ms(utc_time_ticks)) # Output: 1525194379988
Verify the Result
If you take the UTC result (1525194379988) and convert it back to a human-readable time:
import time print(time.gmtime(1525194379988 / 1000))
You'll get:
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=1, tm_hour=17, tm_min=6, tm_sec=19, tm_wday=1, tm_yday=121, tm_isdst=0)
Which aligns perfectly with the Unix timestamp example you provided!
内容的提问来源于stack exchange,提问作者sergeyvin
相关产品推荐
相关产品推荐

