使用 pywin32 在没有时间的情况下在 excel 中写入日期
Write dates in excel without time using pywin32
是否可以在没有时间的情况下使用 pywin32 将日期值写入 excel?即使我创建的 datetime 对象没有时间也没有与之关联的 utc,当将值写入 excel 时,它仍然会添加一个与 utc 相关的小时组件。我该如何解决这个简单的问题?
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)
如果你只想要没有时间的日期,你可以直接调用 datatime.date()
to get it. Unfortunately the value must be converted to a string because the win32com.client
won't accept a datetime.date
对象。
# Writes '1/1/2019'
ws.Cells(1, 1).Value = str(datetime(2019, 1, 1).date())
更新:
您可以通过将 Excel formula
分配给单元格来解决具有文本条目的单元格。这样做将使您可以更轻松地将单元格与其他公式及其其他功能(例如排序、图表等)结合使用。
# Writes 1/1/2019
ws.Cells(1, 1).Formula = datetime(2019, 1, 1).strftime('=DATE(%Y,%m,%d)')
是否可以在没有时间的情况下使用 pywin32 将日期值写入 excel?即使我创建的 datetime 对象没有时间也没有与之关联的 utc,当将值写入 excel 时,它仍然会添加一个与 utc 相关的小时组件。我该如何解决这个简单的问题?
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)
如果你只想要没有时间的日期,你可以直接调用 datatime.date()
to get it. Unfortunately the value must be converted to a string because the win32com.client
won't accept a datetime.date
对象。
# Writes '1/1/2019'
ws.Cells(1, 1).Value = str(datetime(2019, 1, 1).date())
更新:
您可以通过将 Excel formula
分配给单元格来解决具有文本条目的单元格。这样做将使您可以更轻松地将单元格与其他公式及其其他功能(例如排序、图表等)结合使用。
# Writes 1/1/2019
ws.Cells(1, 1).Formula = datetime(2019, 1, 1).strftime('=DATE(%Y,%m,%d)')