【问题标题】:Converting date time to excel style in Pandas在 Pandas 中将日期时间转换为 excel 样式
【发布时间】:2021-08-02 18:11:12
【问题描述】:

我想更改以下格式

2012-12-22
2012-12-24
2012-12-25

转excel样式格式

44120
44121
44123

如何在 pandas 中将 DateTime 格式转换为 excel 样式?

【问题讨论】:

标签: python excel pandas datetime


【解决方案1】:

你可以自己写转换器,纯Python例子:

from datetime import datetime, timezone

def toExcelSerialDate(dt, _origin=datetime(1899,12,30,tzinfo=timezone.utc)):
    """
    convert a datetime object to Excel serial date
    """
    return (dt-_origin).total_seconds()/86400 # output in days since origin

for s in ["2012-12-22", "2012-12-24", "2012-12-25"]:
    print(toExcelSerialDate(datetime.fromisoformat(s).replace(tzinfo=timezone.utc)))
    
# 41265.0
# 41267.0
# 41268.0

应用于熊猫 df:

import pandas as pd

df = pd.DataFrame({'datetime': ["2012-12-22", "2012-12-24", "2012-12-25"]})

# make sure your column is of dtype datetime:
df['datetime'] = pd.to_datetime(df['datetime'])

# subtract origin and convert to days:
df['excelDate'] = (df['datetime']-pd.Timestamp("1899-12-30")).dt.total_seconds()/86400

# df['excelDate']
# 0    41265.0
# 1    41267.0
# 2    41268.0
# Name: excelDate, dtype: float64

【讨论】:

  • 感谢您的评论!我添加以下代码:df['excelDate'].astype(str)。然后输出不是我所期望的。我想知道我可以让 str 类型的“excelDate”看起来像 int 类型。
  • @mevvoy 请注意,Excel 序列日期的来源实际上是“1899-12-31”,因此“1900-01-01”将是第 1 天。使用来源“1899-12-30” " 这里是为了说明 Excel 从 Lotus 123 继承的一个错误,其中 1900 年被认为是闰年(事实上,它不能被 400 整除)。
  • @mevvoy:要使列“看起来像 int”(但实际上是字符串 dtype),请使用 df['excelDate'].astype(int).astype(str)。为什么你需要那个^^
猜你喜欢
  • 1970-01-01
  • 2016-11-22
  • 2015-10-25
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多