python - 将日期从字符串格式转换为 OLE 自动化日期

标签 python python-3.x date datetime ole

我有一个日期字符串 21-Apr-2018。如何将此日期字符串转换为 python 中的 OLE 自动化日期?我正在使用 Python v3.6。

可以在此处找到 OLE 日期的定义。

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.

最佳答案

至少有几种方法。您可以从 OLE 起始日期手动计算,或使用第 3 方库,例如 xlrd .

在每种情况下,您都需要将字符串转换为 datetime 对象。

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

关于python - 将日期从字符串格式转换为 OLE 自动化日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49956741/

相关文章:

python - 计算概率密度平均值python

python - Amazon AWS Cognito 和 Python Boto3 建立 AWS 连接并将文件上传到 Bucket

Python 3.2 : How do you install easy_install

Python3 与 asyncpg 的语法错误

python - Python 3.6+ 中是否有格式化的字节字符串文字?

python - 试图从文本文件中提取有用的信息 block

python - 不显示所有数字的 Django 分页器页面范围

javascript - 将 PHP 日期格式转换为 Javascript 日期格式的函数(不是日期本身!)

MySQL 在日期之间选择留空

mysql - 从当月开始计算年龄