使用 Pandas 转换 Excel 样式的日期 [英] Convert Excel style date with pandas
本文介绍了使用 Pandas 转换 Excel 样式的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须解析一个 xml 文件,该文件以 Excel 样式为我提供日期时间;例如:42580.3333333333
.
I have to parse an xml file which gives me datetimes in Excel style; for example: 42580.3333333333
.
Pandas 是否提供了一种将该数字转换为常规 datetime
对象的方法?
Does Pandas provide a way to convert that number into a regular datetime
object?
推荐答案
OK 我认为最简单的方法是从浮点数构造一个 TimedeltaIndex
并将其添加到 1900 的标量日期时间,1,1
:
OK I think the easiest thing is to construct a TimedeltaIndex
from the floats and add this to the scalar datetime for 1900,1,1
:
In [85]:
import datetime as dt
import pandas as pd
df = pd.DataFrame({'date':[42580.3333333333, 10023]})
df
Out[85]:
date
0 42580.333333
1 10023.000000
In [86]:
df['real_date'] = pd.TimedeltaIndex(df['date'], unit='d') + dt.datetime(1900,1,1)
df
Out[86]:
date real_date
0 42580.333333 2016-07-31 07:59:59.971200
1 10023.000000 1927-06-12 00:00:00.000000
好吧,似乎 excel 的日期有点奇怪,谢谢@ayhan:
OK it seems that excel is a bit weird with it's dates thanks @ayhan:
In [89]:
df['real_date'] = pd.TimedeltaIndex(df['date'], unit='d') + dt.datetime(1899, 12, 30)
df
Out[89]:
date real_date
0 42580.333333 2016-07-29 07:59:59.971200
1 10023.000000 1927-06-10 00:00:00.000000
见相关:如何将python datetime.datetime转换为excel序列日期号
这篇关于使用 Pandas 转换 Excel 样式的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文