我想创建NT格式的网络时间戳。
我已经能够用这个函数将它们转换为可读时间:
NetworkStamp = "xc0x65x31x50xdex09xd2x01"
def GetTime(NetworkStamp):
Ftime = int(struct.unpack('<Q',NetworkStamp)[0])
Epoch = divmod(Ftime - 116444736000000000, 10000000)
Actualtime = datetime.datetime.fromtimestamp(Epoch[0])
return Actualtime, Actualtime.strftime('%Y-%m-%d %H:%M:%S')
print GetTime(NetworkStamp)
输出:(datetime.datetime(2016, 9, 8, 11, 35, 57), '2016-09-08 11:35:57')
现在我想做相反的事情,将'2016/09/08 11:35:57'
秒转换为以下格式:
"xc0x65x31x50xdex09xd2x01"
将窗口的FILETIME
值转换为datetime.datetime
值的代码并不像它可能的那样准确-它截断了可能存在的任何小数秒(因为它忽略了divmod()
结果的其余部分)。这在代码创建的可读字符串中是不明显的,因为它只显示整个秒。
即使包含小数秒,也不能完全按照您的需要进行操作,因为Windows FILETIME
结构的值间隔为100纳秒(纳秒)。1微秒),但Python的datetime
只支持精确到整个微秒。因此,最好的方法就是接近原始值,因为即使进行最精确的转换,也会丢失信息。
NetworkStamp
测试值来演示这一点:
import datetime
import struct
import time
WINDOWS_TICKS = int(1/10**-7) # 10,000,000 (100 nanoseconds or .1 microseconds)
WINDOWS_EPOCH = datetime.datetime.strptime('1601-01-01 00:00:00',
'%Y-%m-%d %H:%M:%S')
POSIX_EPOCH = datetime.datetime.strptime('1970-01-01 00:00:00',
'%Y-%m-%d %H:%M:%S')
EPOCH_DIFF = (POSIX_EPOCH - WINDOWS_EPOCH).total_seconds() # 11644473600.0
WINDOWS_TICKS_TO_POSIX_EPOCH = EPOCH_DIFF * WINDOWS_TICKS # 116444736000000000.0
def get_time(filetime):
"""Convert windows filetime winticks to python datetime.datetime."""
winticks = struct.unpack('<Q', filetime)[0]
microsecs = (winticks - WINDOWS_TICKS_TO_POSIX_EPOCH) / WINDOWS_TICKS
return datetime.datetime.fromtimestamp(microsecs)
def convert_back(timestamp_string):
"""Convert a timestamp in Y=M=D H:M:S.f format into a windows filetime."""
dt = datetime.datetime.strptime(timestamp_string, '%Y-%m-%d %H:%M:%S.%f')
posix_secs = int(time.mktime(dt.timetuple()))
winticks = (posix_secs + int(EPOCH_DIFF)) * WINDOWS_TICKS
return winticks
def int_to_bytes(n, minlen=0): # helper function
""" int/long to bytes (little-endian byte order).
Note: built-in int.to_bytes() method could be used in Python 3.
"""
nbits = n.bit_length() + (1 if n < 0 else 0) # plus one for any sign bit
nbytes = (nbits+7) // 8 # number of whole bytes
ba = bytearray()
for _ in range(nbytes):
ba.append(n & 0xff)
n >>= 8
if minlen > 0 and len(ba) < minlen: # zero pad?
ba.extend([0] * (minlen-len(ba)))
return ba # with low bytes first
def hexbytes(s): # formatting helper function
"""Convert string to string of hex character values."""
ba = bytearray(s)
return ''.join('\x{:02x}'.format(b) for b in ba)
win_timestamp = b'xc0x65x31x50xdex09xd2x01'
print('win timestamp: b"{}"'.format(hexbytes(win_timestamp)))
dtime = get_time(win_timestamp)
readable = dtime.strftime('%Y-%m-%d %H:%M:%S.%f') # includes fractional secs
print('datetime repr: "{}"'.format(readable))
winticks = convert_back(readable) # includes fractional secs
new_timestamp = int_to_bytes(winticks)
print('new timestamp: b"{}"'.format(hexbytes(new_timestamp)))
输出:win timestamp: b"xc0x65x31x50xdex09xd2x01"
datetime repr: "2016-09-08 07:35:57.996998"
new timestamp: b"x80x44x99x4fxdex09xd2x01"
如果您了解如何在一个方向上执行转换,那么反向执行转换基本上就是以相反顺序使用每个方法的逆。只需查看您正在使用的模块/类的文档:
-
strftime
有对应的strptime
-
fromtimestamp
由timestamp
匹配(如果你使用3.3之前的Python,timestamp
不存在,但你可以在函数外定义FILETIME_epoch = datetime.datetime(1601, 1, 1) - datetime.timedelta(seconds=time.altzone if time.daylight else time.timezone)
来预先计算一个datetime
,它代表你的时区的FILETIME
epoch,然后使用int((mydatetime - FILETIME_epoch).total_seconds())
直接获得FILETIME
epoch以来的int
秒,而无需手动调整FILETIME
和Unix epoch之间的差异) -
divmod
(你并不真正需要,因为你只使用商,而不是余数,你可以只做Epoch = (Ftime - 116444736000000000) // 10000000
,以后避免索引)是微不足道的可逆的(只是乘和加,如果你使用我的技巧直接从#2转换为FILETIME
epoch秒,则不需要添加) -
struct.unpack
匹配struct.pack
我没有提供确切的代码,因为你真的应该自己学习使用这些东西(必要时阅读文档);我猜你的前向代码是在不理解它在做什么的情况下编写的,因为如果你理解了它,反向代码应该是显而易见的;
基本转换:
from datetime import datetime
from calendar import timegm
EPOCH_AS_FILETIME = 116444736000000000 # January 1, 1970 as MS file time
HUNDREDS_OF_NANOSECONDS = 10000000
def dt_to_filetime(dt):
return EPOCH_AS_FILETIME + (timegm(dt.timetuple()) * HUNDREDS_OF_NANOSECONDS)
答案是基于这个要点我发现:https://gist.github.com/Mostafa-Hamdy-Elgiar/9714475f1b3bc224ea063af81566d873
Gist增加了对时区和其他方向的转换的支持。