I need to convert filetime to datetime. I am using this code filetime.py, from here as mentioned in this thread Datetime to filetime (Python).
In the code
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
does not take negative value on windows system, so I can't convert filetime before Jan 1st 1970. But I can convert dates before 1970 on Mac using the exact same code (reason here). Is there any workaround for windows?
By adding a timedelta
to a reference date you can use any date formula you'd like. timedelta
is allowed to be positive or negative.
def filetime_to_dt(ft):
us = (ft - EPOCH_AS_FILETIME) // 10
return datetime(1970, 1, 1) + timedelta(microseconds = us)