1

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)

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Your suggestion worked. I have separated pieces of time in the string into hours, minutes and seconds and got a desired result. I am sure there's a more elegant solution for what I'm trying to achieve but this works. Thanks.
@IL3DSM: If you are OK with having a nonzero date portion (honestly, I don't see why not), then use datetime.datetime objects, which can be generated from strings with the strptime method. Also, depending on how you're grabbing the pieces from your string, it might be easier to use the time.strptime method (this doesn't give you a datetime.time object, but rather a named tuple).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.