我正在使用Python从Excel读取数据并对其进行操作。但是日期显示为整数。如何将这些日期转换回日期格式?
5/15/2015 显示为 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)
正如J.F. Sebastian所提到的,此答案仅适用于1900/03/01之后的任何日期。
编辑:(回答@R.K)
如果您的excel_date
是浮点数,请使用此代码:
from datetime import datetime
def floatHourToTime(fh):
hours, hourSeconds = divmod(fh, 1)
minutes, seconds = divmod(hourSeconds * 60, 1)
return (
int(hours),
int(minutes),
int(seconds * 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)
print(dt)
assert str(dt) == "2015-05-15 00:13:55"
模块xlrd
提供函数xldate_as_tuple
,将Excel的数字日期格式转换为元组(年, 月, 日, 时, 分, 秒)
。
然后您可以使用datetime.datetime
将元组转换为datetime
对象。
from datetime import datetime
import xlrd
excel_date = 44032
python_date = datetime(*xlrd.xldate_as_tuple(excel_date, 0))
xlrd.xldate_as_tuple()
的第二个参数是工作簿的“datemode”(即基于1900年或1904年的日期)。最好直接从您的工作簿中传递它。(即您的工作簿的“datemode”属性)。https://xlrd.readthedocs.io/en/latest/dates.html#dates-in-excel-spreadsheets - MinchinWeb
pandas
特定的解决方案,请参见 使用 pandas 转换 Excel 样式日期。 - FObersteiner