用 pandas 转换Excel样式日期 [英] Convert Excel style date with pandas

查看:61
本文介绍了用 pandas 转换Excel样式日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须解析一个XML文件,该文件为我提供Excel样式的日期时间;例如:42580.3333333333.

I have to parse an xml file which gives me datetimes in Excel style; for example: 42580.3333333333.

熊猫提供了一种将该数字转换为常规datetime对象的方法吗?

Does Pandas provide a way to convert that number into a regular datetime object?

推荐答案

好的,我认为最简单的方法是从浮点数构造一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆