Working with Active Directory FILETIME values in Python

[How To Convert a UNIX time_t to a Win32 FILETIME or SYSTEMTIME][kb]:

> Under Win32 platforms, file times are maintained primarily in the form of
> a 64-bit FILETIME structure, which represents the number of 100-nanosecond
> intervals since January 1, 1601 UTC (coordinate universal time).

***UPDATED* New version with fixes by Tim Williams for preserving microseconds. See [here for details][updated].**

It just so happens that [Microsoft Active Directory][msad] uses the same 64-bit value to store some time values. For example [the `accountExpires` attribute][expires] is in this format. Linked below is a module for Python with utility functions for converting between [Python’s datetime instances][datetime] and Microsoft’s FILETIME values.

Very handy if you enjoy querying Active Directory for login accounts that are due to expire. And who wouldn’t enjoy that? On a Monday.

[Download module for converting between FILETIME and `datetime` objects.][filetimes] This code is released under a 2-clause BSD license.

Example usage:

>>> from filetimes import filetime_to_dt, dt_to_filetime, utc
>>> filetime_to_dt(116444736000000000)
datetime.datetime(1970, 1, 1, 0, 0)
>>> filetime_to_dt(128930364000000000)
datetime.datetime(2009, 7, 25, 23, 0)
>>> “%.0f” % dt_to_filetime(datetime(2009, 7, 25, 23, 0))
>>> dt_to_filetime(datetime(1970, 1, 1, 0, 0, tzinfo=utc))
>>> dt_to_filetime(datetime(1970, 1, 1, 0, 0))

I even remembered to write tests for once!

[filetimes]: /b/wp-content/

5 thoughts on “Working with Active Directory FILETIME values in Python

  1. Pingback: Reliably Broken » Free software FTW! Updated

  2. Marcus Schommler

    Very helpful indeed, I was looking around for quite a while until I finally found this. Exactly what I was needing.

  3. Marcus Schommler

    Just one thing I noticed after using your code to convert user LastLogon values from AD. The function filetime_to_dt chokes on the line ‘dt = datetime.utcfromtimestamp(s)’ if ft is 0. Shouldn’t the result for that value be equivalent to datetime(1601,1,1,0,0,0,0)?

    If you like me to explain how it comes that I’ve been running into using 0 as a parameter to this function, I’m willing to do it :-)

Leave a Reply

Your email address will not be published. Required fields are marked *