Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python convert filetime to datetime for dates before 1970

Tags:

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?

like image 491
Echo Avatar asked Aug 10 '16 16:08

Echo


People also ask

How do I convert a datetime to a specific date in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

How do I convert a string to a datetime in Python?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

How do you convert dd mm to yyyy in Python?

yyyy-mm-dd stands for year-month-day . We can convert string format to datetime by using the strptime() function. We will use the '%Y/%m/%d' format to get the string to datetime.


1 Answers

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)
like image 156
Mark Ransom Avatar answered Sep 23 '22 16:09

Mark Ransom