2015-04-01 112 views
6

我有一個值38142我需要使用python將其轉換爲日期格式。 如果在excel中使用這個數字,並在那時做一個右鍵點擊和格式化單元格的值將被轉換爲04/06/2004,我需要使用python相同的結果。我怎樣才能達到這個目標如何將給定的序號(從Excel)轉換爲日期

+0

這是一個奇怪的序數;你確定04/06/2004是正確的嗎?如果價值38142代表* days *,那麼這將是1993/12/25或1993/10/27的偏移量,具體取決於您解釋的月份。 – 2015-04-01 09:29:18

+0

[將日期轉換爲數字的公式](http://stackoverflow.com/q/19721416)表明它應該是自1900/01/01以來的幾天,這是'date.fromordinal()'的作用。但那個號碼就是一個數字。 – 2015-04-01 09:30:40

+0

我的文件有值我不知道它的序號或不是我的客戶說它的序號,並告訴我,「如果你想找到實際的日期只是格式單元格在Excel中的給定值,那時我得到這個值「@MartijnPieters – Krish 2015-04-01 09:39:40

回答

10

在1900/01/01 Excel中的偏移量;增加的天數爲timedelta:

from datetime import date, timedelta 

def from_excel_ordinal(ordinal, _epoch=date(1900, 1, 1)): 
    if ordinal > 59: 
     ordinal -= 1 # Excel leap year bug, 1900 is not a leap year! 
    return _epoch + timedelta(days=ordinal - 1) # epoch is day 1 

我不得不調整由的依次爲1900年2月28日之後的任何日期; Excel從Lotus 1-2-3繼承了leap year bug,並將1900作爲閏年。上述代碼爲5960返回date(1900, 2, 28)以解決此問題。

+0

這是完美的,非常感謝你@Martijn Pieters – Krish 2015-04-01 09:47:09

+0

@Krish:這個bug被Joel Spolsky推廣:[My First BillG Review](http://www.joelonsoftware.com/items/2006/06/16.html) – jfs 2015-04-02 20:07:45

+0

你確定這個時代不是1899年12月31日? datetime(1899,12,31)+ timedelta(ordinal - (ordinal> 59))' – jfs 2015-04-02 20:20:35

2
from datetime import datetime, timedelta 

def from_excel_ordinal(ordinal, epoch=datetime(1900, 1, 1)): 
    # Adapted from above, thanks to @Martijn Pieters 

    if ordinal > 59: 
     ordinal -= 1 # Excel leap year bug, 1900 is not a leap year! 
    inDays = int(ordinal) 
    frac = ordinal - inDays 
    inSecs = int(round(frac * 86400.0)) 

    return epoch + timedelta(days=inDays - 1, seconds=inSecs) # epoch is day 1 

excelDT = 42548.75001   # Float representation of 27/06/2016 6:00:01 PM in Excel format 
pyDT = from_excel_ordinal(excelDT) 

上面的答案對於日期值來說很好,但是在這裏我擴展了上面的解決方案以包含時間並返回datetime值。

相關問題