Search code examples
pythonpywin32

Write dates in Excel without time using pywin32


Is it possible to write date values using pywin32 to Excel without the time? Even though the datetime object I create has no time nor UTC associated to it, when writing the value to Excel it still adds an hour component which is related to UTC. How can I solve this simple problem?

import win32com.client
from datetime import datetime

excel = win32com.client.Dispatch('Excel.Application')
excel.Visible = True
wb = excel.Workbooks.Add()
ws = wb.Sheets['Sheet1']

# Writes '01/01/2019 03:00:00' instead of '01/01/2019'
ws.Cells(1, 1).Value = datetime(2019, 1, 1)


Solution

  • If you just want the date with no time of day, you can call datatime.date() to get it. Unfortunately the value must be converted to a string because the win32com.client won't accept a datetime.date object directly.

    # Writes '1/1/2019'
    ws.Cells(1, 1).Value = str(datetime(2019, 1, 1).date())
    

    Update:
    You can workaround the cell having a text entry by assigning an Excel formula to the cell instead. Doing this will allow you to use the cell more easily in conjunction with other formulas and its other capabilities (such as sorting, charting, etc).

    # Writes 1/1/2019
    ws.Cells(1, 1).Formula = datetime(2019, 1, 1).strftime('=DATE(%Y,%m,%d)')