【问题标题】:read xlsb file as pandas dataframe and parse the date column as datetime format将 xlsb 文件读取为 pandas 数据框并将日期列解析为日期时间格式
【发布时间】:2021-09-02 00:43:37
【问题描述】:

我有一个包含大约 10 列的“some.xlsb”文件,其中 2 列是 DateTime 列。

当我使用 pandas 加载时,日期时间列会以不同的形式解析。

解释:

其中DateTime 值对应于4/10/2021 11:50:24 AM - 读作44296.5

下面是我试过的代码。

goods_df = pd.read_excel('some.xlsb',
                   engine='pyxlsb', sheet_name='goods_df')

goods_df_header = goods_df.iloc[1]
goods_df.columns = goods_df_header #set the header row as the df header
goods_df= goods_df[2:]
goods_df.head(2)

【问题讨论】:

标签: python-3.x pandas dataframe datetime pyxlsb


【解决方案1】:

当您使用 pandas 读取 xlsb 文件时,您将获得 excel 时间浮点值,因为 xlsb 在存储之前将日期时间对象转换为浮点值。

根据 Microsoft 44296.5 表示自 1900 年 1 月 1 日以来已过去 44296.5 天。

您需要将其转换为纪元,然后使用以下公式确定日期(纪元值 = 自 1970 年 1 月 1 日 00:00:00 以来经过的秒数)。

a = datetime.datetime.strftime((int(<datevalue from excel>)*86400)-2207520000, "%m/%d/%Y")

或者您可以将此 xlsb 保存为 xlsx 并阅读它,您将获得准确的日期时间对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 2021-06-14
    • 2018-02-18
    • 1970-01-01
    • 2021-04-11
    • 2017-08-03
    相关资源
    最近更新 更多