首页 > 解决方案 > 在 Pandas 中将日期时间转换为 excel 样式

问题描述

我想更改以下格式

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

转为 excel 样式格式

44120
44121
44123

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

标签: pythonexcelpandasdatetime

解决方案


您可以编写自己的转换器,纯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

推荐阅读