python - 在 Pandas 中将日期时间转换为 excel 样式
问题描述
我想更改以下格式
2012-12-22
2012-12-24
2012-12-25
转为 excel 样式格式
44120
44121
44123
如何将 DateTime 格式转换为 pandas 中的 excel 样式?
解决方案
您可以编写自己的转换器,纯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
推荐阅读
- python-3.x - 出现错误“pywintypes.error: (5, 'OpenClipboard', 'Access is denied.')”
- php - 提交后未找到联系表错误
- java - 我已经使用 viewpager 和图像网址创建了一个壁纸应用程序,但我无法设置壁纸我将我的网址放在字符串中
- sql-server - powershell 设置数据库设置
- haskell - Haskell 中的重载(显示和编号)
- java - JFreechart - 带有颜色图的极坐标图
- r - 用条件将值替换到上一行
- xamarin.forms - Xamarin 表单:当键盘打开时,顶部堆栈布局在 UI 中不可见
- angular - Angular 反应形式禁用组
- reactjs - 在antd中预览上传的图片