سؤال

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