将日期从Excel以数字格式转换为日期格式python [英] Convert date from excel in number format to date format python
本文介绍了将日期从Excel以数字格式转换为日期格式python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从excel中读取数据并使用python处理数据。但是日期是整数。如何将日期转换回日期格式?
I am reading data from excel and manipulating the data using python. But dates are coming as integers. How can I convert the dates back to date format?
2015年5月15日将为42139.00
5/15/2015 is coming as 42139.00
推荐答案
from datetime import datetime
excel_date = 42139
dt = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + excel_date - 2)
tt = dt.timetuple()
print dt
print tt
正如JF Sebastian所述,此答案仅适用于1900/03/01之后的任何日期
As mentioned by J.F. Sebastian, this answer only works for any date after 1900/03/01
编辑:(以@表示) RK)
(in answer to @R.K)
如果您的 excel_date
是浮点数,请使用以下代码:
If your excel_date
is a float number, use this code:
def floatHourToTime(fh):
h, r = divmod(fh, 1)
m, r = divmod(r*60, 1)
return (
int(h),
int(m),
int(r*60),
)
excel_date = 42139.23213
dt = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + int(excel_date) - 2)
hour, minute, second = floatHourToTime(excel_date % 1)
dt = dt.replace(hour=hour, minute=minute, second=second)
这篇关于将日期从Excel以数字格式转换为日期格式python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文