So, given:
dttm = datetime.datetime.strptime("2014-06-23 13:56:30", "%Y-%m-%d %H:%M:%S")
ws['A1'] = dttm
The result in excel is that the correct date-time is written to the cell (you can see it where you'd input formulas). BUT, the cell display format is only MM/DD/YYYY.
I need the cell to display like "6/23/2014 13:56" instead of just "6/23/2014".
How can I explicitly format the cell to accomplish this?
Thanks!
Edit
@alecxe This solution works and is exactly what I asked for. I would like to be able to save styles like the solution by @Woodham. Unfortunately it raises a typeError (see comment). Any suggestions?
For openpyxl 2.3.4 the NumberFormat cannot be imported, but this code works to set the style:
I believe you will need to set a
openpyxl.styles.Style
on the cell(s) that you want to format.Looking at the documentation here, something like this should work:
Update: Style class is no longer used, for the solution refer to this answer.
For openpyxl 2.4.5 you'll no longer have access to
NumberFormat
andStyle
and will have to useNamedStyle
. Here's some sample usage:Alternatively with the new
NamedStyle
class, you can set the style by the string name onceNamedStyle
has been instantiated:Documentation here: http://openpyxl.readthedocs.io/en/default/styles.html#creating-a-named-style
I'm adding this as a new answer since I don't have enough reputation to add a comment to the above. The simplest way to format a cell is using .number_format = "format" as in:
This is tested in openpyxl (2.2.2)
You can manually set the
format_code
:Alternatively, you can call
_set_number_format()
method on the cell:You can also define the style and reuse it, by setting
ws._styles
for a cell:Tested - worked for me.