我需要将filetime转换为datetime。我正在使用filetime.py中的代码here,如此帖子Datetime to filetime (Python)中所述。
在代码中
EPOCH_AS_FILETIME = 116444736000000000 # January 1, 1970 as MS file time
HUNDREDS_OF_NANOSECONDS = 10000000
def filetime_to_dt(ft):
"""Converts a Microsoft filetime number to a Python datetime. The new datetime object is time zone-naive but is equivalent to tzinfo=utc.
>>> filetime_to_dt(116444736000000000)
datetime.datetime(1970, 1, 1, 0, 0)
"""
# Get seconds and remainder in terms of Unix epoch
(s, ns100) = divmod(ft - EPOCH_AS_FILETIME, HUNDREDS_OF_NANOSECONDS)
# Convert to datetime object
dt = datetime.utcfromtimestamp(s)
# Add remainder in as microseconds. Python 3.2 requires an integer
dt = dt.replace(microsecond=(ns100 // 10))
return dt
datetime.utcfromtimestamp
在Windows系统上没有负值,所以我无法在1970年1月1日之前转换文件时间。但是我可以使用完全相同的代码在Mac上转换1970年之前的日期(原因{{3 }})。是否有Windows的解决方法?
答案 0 :(得分:3)
通过在参考日期添加timedelta
,您可以使用您想要的任何日期公式。 timedelta
被允许为正面或负面。
def filetime_to_dt(ft):
us = (ft - EPOCH_AS_FILETIME) // 10
return datetime(1970, 1, 1) + timedelta(microseconds = us)
答案 1 :(得分:1)
According to docs,您必须使用:
dt = datetime.fromtimestamp(s, datetime.timezone.utc)
而不是:
dt = datetime.utcfromtimestamp(s)
答案 2 :(得分:0)
首先,您需要将其转换为可识别的文件时间格式,如下所示:
>>> dwLowDateTime = 0x0F7297A80
>>> dwHighDateTime = 0x1C3F10F << 32
>>> ft = (dwLowDateTime & 0xFFFFFFFF) | dwHighDateTime
127210265370000000
然后使用此脚本,它将文件时间转换为日期时间,反之亦然https://gist.github.com/Mostafa-Hamdy-Elgiar/9714475f1b3bc224ea063af81566d873
>>> filetime_to_dt(ft)
2004-02-12 02:28:57
答案 3 :(得分:0)
使用timedelta
s在时间范围内加/减/除:
FILE_TIME_EPOCH = datetime.datetime(1601, 1, 1)
FILE_TIME_MICROSECOND = 10 # FILETIME counts 100 nanoseconds intervals = 0.1 microseconds, so 10 of those are 1 microsecond
def convert_from_file_time(file_time):
microseconds_since_file_time_epoch = file_time // FILE_TIME_MICROSECOND
return FILE_TIME_EPOCH + datetime.timedelta(microseconds=microseconds_since_file_time_epoch)
另一面是:
def convert_to_file_time(date_time):
microseconds_since_file_time_epoch = (date_time - FILE_TIME_EPOCH) // datetime.timedelta(microseconds=1)
return microseconds_since_file_time_epoch * FILE_TIME_MICROSECOND