问题
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.
回答1:
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
来源:https://stackoverflow.com/questions/49956741/convert-date-from-string-format-to-ole-automation-date