문제

I can convert date read from excel to a proper date using xldate_as_tuple function. Is there any function which can do the reverse i.e. convert proper date to float which is stored as date in excel ?

도움이 되었습니까?

해결책

In the xlrd xldate.py module there are several functions, xldate_from_date_tuple(), xldate_from_time_tuple() and xldate_from_datetime_tuple(), which convert datetime objects to Excel series dates.

Also, in the XlsxWriter utility.py module there is a function called datetime_to_excel_datetime() which converts datetime objects for an Excel serial date.

All of these solutions take into account the epoch and the Excel 1900 leapyear bug.

다른 팁

Excel dates are represented as pywintypes.Time type objects. So in order to e.g. assign the current timestamp to a cell you do:

workbook.Worksheets(1).Cells(1,1).Value = pywintypes.Time(datetime.datetime.now())

Almost Bjoern Stiel's answer (tried to up arrow but don't have enough reputation).

Had to add tz_info (used pytz for this):

    from win32com.client import Dispatch
    xlApp = Dispatch("Excel.Application")
    book = xlApp.Workbooks.Open(r"C:\Path\to\file")
    d = pytz.utc.localize(datetime.datetime.now())
    book.Sheets(1).Cells(2,12).Value = d
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top