如何将python datetime.datetime转换为Excel序列date编号

我需要将date转换为Excel序列号,以便编写一个数据消除脚本。 通过在OpenOffice Calc工作簿中玩date,我可以推断出“1899年1月1日00:00:00”映射到数字零。

我写了下面的函数将python datetime对象转换为Excel序列号:

def excel_date(date1): temp=dt.datetime.strptime('18990101', '%Y%m%d') delta=date1-temp total_seconds = delta.days * 86400 + delta.seconds return total_seconds 

但是,当我尝试一些示例date时,这些数字与我在Excel中格式化date(以及OpenOffice Calc)时得到的数字不同。 例如,testing“2009-03-20”在Python中给出了3478032000,而excel将序列号呈现为39892。

上面的公式有什么问题?

*注:我正在使用Python 2.6.3,所以没有访问datetime.total_seconds()

看来,Excel“序列date”格式实际上是自1900-01-00以来的天数,基于http://www.cpearson.com/excel/datetime的小数部分是一天的几分之一。 htm 。 (我想这个date实际上应该被认为是1899-12-31,因为没有一个月的第0天这样的事情)

所以,它应该是这样的:

 def excel_date(date1): temp = dt.datetime(1899, 12, 30) # Note, not 31st Dec but 30th! delta = date1 - temp return float(delta.days) + (float(delta.seconds) / 86400) 

虽然这与excel序列date格式不完全相关,但这是将pythondate时间导出到Excel的首要条件。 我发现特别有用和简单的是只使用strftime导出。

 import datetime current_datetime = datetime.datetime.now() current_datetime.strftime('%x %X') 

这将以Excel的接受格式'06 / 25/14 09:59:29'输出为有效的date/时间,并允许在Excel中进行sorting。

如果问题是我们想为date使用DATEVALUE()excel序列号,则可以使用toordinal()函数。 Python的序列号从1年的1月份开始,而Excel从1900年1月1日开始,所以应用一个偏移量。 另请参阅excel 1900闰年错误( https://support.microsoft.com/en-us/help/214326/excel-incorrectly-assumes-that-the–19-19-is-a-leap-year

 def convert_date_to_excel_ordinal(day, month, year) : offset = 693594 current = date(year,month,day) n = current.toordinal() return (n - offset)