DenisS
DenisS

Reputation: 46

Python XLWT - Issue with custom format

I am trying to put time into a cell. I need it to be independent without the year, month, day data datetime appends.
When I try writing a string 15:55:00 with format h:mm AM/PM it shows up as 15:55:00 on the excel sheet until I select the cell and press enter, so it seems that this isn't a valid way to do it.

Passing datetime works but again, I do not want to have date information in my cell, just properly formatted time.

My current code is as follows:

style = XFStyle()
style.num_format_str = 'h:mm:ss AM/PM'
time = "15:22:00"
ws.write(i, 4, time, style)

Upvotes: 1

Views: 673

Answers (1)

John Y
John Y

Reputation: 14529

First of all, there is no such thing in Excel as a time without a date. The value of a cell can be formatted so that the date portion doesn't show up, but it's still stored in the cell no matter what.

When you enter a time manually into Excel, it assumes a date of zero (which Excel will happily display as January 0, 1900 given the proper formatting). If this is what you want to replicate using xlwt, then simply use a Python datetime.time object instead of a datetime.datetime:

import datetime

style = XFStyle()
style.num_format_str = 'h:mm:ss AM/PM'
time = datetime.time(hour=15, minute=22, second=0)
ws.write(i, 4, time, style)

Upvotes: 1

Related Questions