Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date from string format to OLE automation date

I have a date string 21-Apr-2018. How do I convert this date string into OLE automation date in python? I am using Python v3.6.

Definition of OLE date can be found here.

https://msdn.microsoft.com/en-us/library/system.datetime.tooadate(v=vs.110).aspx

An OLE Automation date is implemented as a floating-point number whose integral component is the number of days before or after midnight, 30 December 1899, and whose fractional component represents the time on that day divided by 24. For example, midnight, 31 December 1899 is represented by 1.0; 6 A.M., 1 January 1900 is represented by 2.25; midnight, 29 December 1899 is represented by -1.0; and 6 A.M., 29 December 1899 is represented by -1.25.

The base OLE Automation Date is midnight, 30 December 1899. The minimum OLE Automation date is midnight, 1 January 0100. The maximum OLE Automation Date is the same as DateTime.MaxValue, the last moment of 31 December 9999.

like image 967
user1315789 Avatar asked Feb 04 '26 07:02

user1315789


1 Answers

There are at least a couple of ways. You can calculate manually from OLE origin date, or use a 3rd party library such as xlrd.

In each case, you will need to convert your string to a datetime object.

from datetime import datetime
from xlrd import xldate

def datetime2ole(date):
    date = datetime.strptime(date, '%d-%b-%Y')
    OLE_TIME_ZERO = datetime(1899, 12, 30)
    delta = date - OLE_TIME_ZERO
    return float(delta.days) + (float(delta.seconds) / 86400)  # 86,400 seconds in day

def datetime2xl(date):
    date = datetime.strptime(date, '%d-%b-%Y')
    parts = ('year', 'month', 'day', 'hour', 'minute', 'second')
    components = tuple(getattr(date, x) for x in parts)
    return xldate.xldate_from_datetime_tuple(components, 0)

print(datetime2ole('22-Apr-2018'))  # 43212.0
print(datetime2xl('22-Apr-2018'))   # 43212.0
like image 154
jpp Avatar answered Feb 05 '26 21:02

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!