将日期时间转换回Windows 64位文件时间

2024-05-14 16:51:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建NT格式的网络时间戳。在

我已经能够用这个函数将它们转换为可读时间:

NetworkStamp = "\xc0\x65\x31\x50\xde\x09\xd2\x01"

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)

输出:

^{pr2}$

现在我要做相反的操作,将'2016/09/08 11:35:57'秒转换为以下格式:

 "\xc0\x65\x31\x50\xde\x09\xd2\x01"

Tags: 格式时间x01epochxdexc0x65x09
2条回答

{{s}可能会忽略{cd2}的余数,因为它可能会忽略^ cd2>的余数。这在代码创建的可读字符串中并不明显,因为它只显示整秒钟。
即使包含分数秒,也不能完全按照您的意愿进行操作,因为Windows FILETIME结构的值间隔为100纳秒(.1微秒),但是Python的datetime只支持精确到整微秒。因此,最好的办法是,由于信息的丢失,即使是最精确的转换,也要近似原始值。在

下面是python2和Python 3的代码,使用问题中的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'\xc0\x65\x31\x50\xde\x09\xd2\x01'
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)))

输出:

^{pr2}$

如果你了解如何在一个方向上执行转换,那么反向操作基本上就是以相反的顺序使用每个方法的逆操作。只需查看您正在使用的模块/类的文档:

  1. strftime有{a1}
  2. fromtimestampis matched by ^{}(如果您使用的是3.3python之前的版本,timestamp不存在,但是您可以在函数之外定义FILETIME_epoch = datetime.datetime(1601, 1, 1) - datetime.timedelta(seconds=time.altzone if time.daylight else time.timezone)来预计算一个datetime表示时区的FILETIMEepoch,然后使用int((mydatetime - FILETIME_epoch).total_seconds())直接获得{}秒,因为{}epoch,无需手动调整FILETIME和Unix epoches之间的差异)
  3. divmod(这不是你真正需要的,因为你只使用商,而不是余数,你可以只做Epoch = (Ftime - 116444736000000000) // 10000000并避免以后索引)是微不足道的可逆的(只要乘法和加法,如果你使用我的技巧直接从#2转换为FILETIMEepoch seconds,那么加法就不必要了)
  4. struct.unpackis matched by ^{}

我没有提供确切的代码,因为你真的应该学会自己使用这些东西(必要时还可以阅读文档);我猜你的前向代码是在不理解它在做什么的情况下编写的,因为如果你理解了它,反过来应该很明显;每一步都在同一页上有一个相反的文档。在

相关问题 更多 >

    热门问题