繁体   English   中英

将 pandas 日期时间列转换为 Excel 序列日期

[英]Convert pandas datetime column to Excel serial date

I have a pandas dataframe with date values, however, I need to convert it from dates to text General format like in Excel, not to date string, in order to match with primary keys values in SQL, which are, unfortunately, reordered in general格式。 是否可以做到 Python 或将此列转换为 Excel 中的一般格式的唯一方法?

以下是数据框列的样子:

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

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

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

这篇文章的启发,你可以做...

data = pd.DataFrame({'ID': ['1/1/2022','7/21/2024','1/1/1931']})
data['General format'] = (
    pd.to_datetime(data["ID"]) - pd.Timestamp("1900-01-01")
    ).dt.days + 2
print(data)
          ID  General format
0   1/1/2022           44562
1  7/21/2024           45494
2   1/1/1931           11324

+2是因为:

  1. Excel 从 1 而不是 0 开始计数
  2. Excel 错误地将 1900 年视为闰年

首先,确定数据类型。 然后,您将有更多的工作要做。 您可以使用 '.astype()' 来更改数据的类型,使用迭代器来删除 '/' 标记,或使用其他方法来更改它。

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

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

请参阅如何计算两个给定日期之间的天数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM