How to format cell with datetime object of the form 'yyyy-mm-dd hh:mm:ss' in Excel using openpyxl

拟墨画扇 提交于 2019-11-30 23:37:08

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:

value = datetime.datetime.strptime("2014-06-23 13:56:30", "%Y-%m-%d %H:%M:%S")
cell = ws['A1']
cell.value = value
cell.number_format = 'YYYY MMM DD'

This is tested in openpyxl (2.2.2)

quetzaluz

For openpyxl 2.4.5 you'll no longer have access to NumberFormat and Style and will have to use NamedStyle. Here's some sample usage:

from openpyxl.styles import NamedStyle

date_style = NamedStyle(name='datetime', number_format='DD/MM/YYYY HH:MM:MM')
ws['A1'].style = date_style

Alternatively with the new NamedStyle class, you can set the style by the string name once NamedStyle has been instantiated:

from openpyxl.styles import NamedStyle

NamedStyle(name='custom_datetime', number_format='DD/MM/YYYY HH:MM:MM')
ws['A1'].style = 'custom_datetime'

Documentation here: https://openpyxl.readthedocs.io/en/stable/styles.html

You can manually set the format_code:

value = datetime.datetime.strptime("2014-06-23 13:56:30", "%Y-%m-%d %H:%M:%S")
cell = ws['A1']
cell.value = value
cell.style.number_format.format_code = 'MM/DD/YY HH:MM'

Alternatively, you can call _set_number_format() method on the cell:

cell._set_number_format('MM/DD/YY HH:MM')

You can also define the style and reuse it, by setting ws._styles for a cell:

from openpyxl.styles import NumberFormat, Style

...

style = Style()
style.number_format = NumberFormat()
style.number_format.format_code = 'MM/DD/YY HH:MM'

ws['A1'] = value
ws._styles['A1'] = style

Tested - worked for me.

For openpyxl 2.3.4 the NumberFormat cannot be imported, but this code works to set the style:

from openpyxl.styles import Style

…
date_style = Style(number_format="DD/MM/YYYY HH:MM:MM")
ws['A1'].style = date_style
Woodham

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:

dttm = datetime.datetime.strptime("2014-06-23 13:56:30", "%Y-%m-%d %H:%M:%S")
s = Style(number_format=NumberFormat('dd-mm-yyyy h:mm:ss'))

ws['A1'] = dttm
ws['A1'].styles = s

Update: Style class is no longer used, for the solution refer to this answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!