【问题标题】:Convert pandas datetime column to Excel serial date将 pandas 日期时间列转换为 Excel 序列日期
【发布时间】:2021-12-30 20:49:29
【问题描述】:

我有一个带有日期值的 pandas 数据框,但是,我需要将它从日期转换为文本一般格式,如 Excel 中,而不是日期字符串,以便与 SQL 中的主键值匹配,不幸的是,以一般格式重新排序。是否可以使用 Python 或将此列转换为 Excel 中的一般格式的唯一方法?

数据框的列如下所示:

   ID         Desired Output
1/1/2022        44562
7/21/2024       45494
1/1/1931        11324

【问题讨论】:

  • 输出代表什么?
  • this 回答你的问题了吗?
  • 它们是通用格式的这些日期,如果您将 excel 中的这些日期列格式从短日期更改为通用,它将显示此输出

标签: python excel pandas datetime


【解决方案1】:

是的,这是可能的。 Excel 中的一般格式从日期 1900-1-1 开始计算天数。

您可以计算 ID 中的日期与 1900-1-1 之间的时间差。

受到this post 的启发,你可以做...

import pandas as pd

from datetime import date

# create a data frame
data = pd.DataFrame({'ID': ['1/1/2022','7/21/2024','1/1/1931']})

# convert the strings in ID to a datetime, then into a series with squeeze and then to a date format. The date format is helpful when calculating time deltas.

sr = pd.to_datetime(data['ID'], format= '%m/%d/%Y').squeeze().dt.date

# Calculate the time deltas by subtracting 1900-1-1 from date in sr and store it in the General format column of data.

data['General format'] =  sr.apply(lambda x: (x - date(1900, 1, 1)).days +2 ).to_frame()

print(data)

          ID  General format
0   1/1/2022           44562
1  7/21/2024           45494
2   1/1/1931           11324

这里有点不简洁...

import pandas as pd

from datetime import date

data = pd.DataFrame({'ID': ['1/1/2022','7/21/2024','1/1/1931']})

ID_to_datetime = pd.to_datetime(data['ID'], format= '%m/%d/%Y')

ID_to_datetime_to_series = ID_to_datetime.squeeze() 

ID_to_datetime_to_series_to_date = ID_to_datetime_to_series.dt.date 

General_format = []

for a_date in ID_to_datetime_to_series_to_date:
   
   timedelta = a_date - date(1900, 1, 1) 
   
   General_format.append(timedelta.days + 2 )

data['General format'] =  General_format

print(data)

          ID  General format
0   1/1/2022           44562
1  7/21/2024           45494
2   1/1/1931           11324

加 2 试图处理闰年。对于您提供的日期,+2 似乎是正确的,但您应该验证这一点。

编辑

仅根据 MrFuppes 的建议使用 pandas

data = pd.DataFrame({'ID': ['1/1/2022','7/21/2024','1/1/1931']})
data['General format'] =  (pd.to_datetime(data["ID"])-pd.Timestamp("1899-12-30")).dt.days
print(data)

我猜熊猫正在处理闰年?

【讨论】:

  • 关于您的问题,是的,pandas datetime 负责闰年(就像 Python datetime 一样)。在 1900-01-01 中添加 2 天是必要的,因为 1) Excel 从 1 开始计数,而不是 2) 它认为 1900 年是闰年,我认为这是从 Lotus 123 继承的错误。
  • 如果您想了解更多背景信息,请查看 my answer here 并点击链接。
【解决方案2】:

Excel 将日期存储为连续的序列号,以便它们可以 用于计算。默认情况下,1900 年 1 月 1 日是序列号 1, 2008 年 1 月 1 日是序列号 39448,因为它是 39,447 天 1900 年 1 月 1 日之后。
-微软的documentation

所以你可以计算(difference between your date and January 1, 1900) + 1

How to calculate number of days between two given dates

【讨论】:

    猜你喜欢
    • 2021-01-05
    • 2021-10-05
    • 2016-10-05
    • 2017-01-28
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 2023-03-17
    • 2020-09-20
    相关资源
    最近更新 更多