Welcome, guest | Sign In | My Account | Store | Cart

This recipe show how to convert OLE datetime values (as used by PyTime from the pywin32 extensions) into Python datetime objects.

Python, 39 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#
# This is all you need to actually do the conversion

import datetime

OLE_TIME_ZERO = datetime.datetime(1899, 12, 30, 0, 0, 0)

def ole2datetime(oledt):
    return OLE_TIME_ZERO + datetime.timedelta(days=float(oledt))

#
#  The rest is just test code

import unittest
import pywintypes

class TestOleConversion(unittest.TestCase):

    def testEpochZero(self):
        """Tests time values compare for value of zero epoch seconds."""
        self.assertEqual(datetime.datetime(1970, 1, 1),
            ole2datetime(pywintypes.Time(0)))

    def testExamplesFromMFC(self):
        """Tests examples from the MFC DATE documentation."""
        for example in (
            #(year, month, day, hour, minute, second, OLE),
            (1899,    12,  30,    0,      0,      0, 0.0),   # 30 December 1899, midnight
            (1900,    01,  01,    0,      0,      0, 2.0),   # 1 January 1900, midnight
            (1900,    01,  04,    0,      0,      0, 5.0),   # 4 January 1900, midnight
            (1900,    01,  04,    6,      0,      0, 5.25),  # 4 January 1900, 6 A.M.
            (1900,    01,  04,   12,      0,      0, 5.5),   # 4 January 1900, noon
            (1900,    01,  04,   21,      0,      0, 5.875), # 4 January 1900, 9 P.M.
            ):
            expected = datetime.datetime(*example[:-1])
            self.assertEqual(expected, ole2datetime(example[-1]))        

if __name__ == '__main__':
    unittest.main()

The pywintypes.Time type doesn't handle explicit initialization OLE values (AFAIK), but if you work with Access via ADO or similar you may get datetime values that our outside of the range handled by epoch seconds (e.g. earlier than 1970), so it is useful to convert from the OLE floating point values in these cases.

1 comment

Brian Boonstra 17 years, 10 months ago  # | flag

Worked great for me. I was fetching Bloomberg data using COM and the trade times came back as PyTime objects. This handled the conversion perfectly.