所以,给定:
dttm = datetime.datetime.strptime("2014-06-23 13:56:30", "%Y-%m-%d %H:%M:%S")
ws['A1'] = dttm
excel中的结果是将正确的日期时间写入单元格(您可以在输入公式的位置看到它)。但是,单元格显示格式仅为MM / DD / YYYY。
我需要显示单元格" 6/23/2014 13:56"而不只是" 6/23/2014"。
如何明确格式化单元格以实现此目的?
谢谢!
@alecxe此解决方案有效,正是我所要求的。我希望能够像@Woodham一样保存解决方案。不幸的是,它引发了一个typeError(请参阅注释)。有什么建议吗?
答案 0 :(得分:10)
我将此添加为新答案,因为我没有足够的声誉来为上述内容添加评论。格式化单元格的最简单方法是使用.number_format ="格式"如:
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'
这是在openpyxl(2.2.2)
中测试的答案 1 :(得分:6)
对于openpyxl 2.4.5,您将无法再访问NumberFormat
和Style
,并且必须使用NamedStyle
。以下是一些示例用法:
from openpyxl.styles import NamedStyle
date_style = NamedStyle(name='datetime', number_format='DD/MM/YYYY HH:MM:MM')
ws['A1'].style = date_style
或者使用新的NamedStyle
类,您可以在实例化NamedStyle
后按字符串名称设置样式:
from openpyxl.styles import NamedStyle
NamedStyle(name='custom_datetime', number_format='DD/MM/YYYY HH:MM:MM')
ws['A1'].style = 'custom_datetime'
此处的文档:http://openpyxl.readthedocs.io/en/default/styles.html#creating-a-named-style
答案 2 :(得分:1)
您可以手动设置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'
或者,您可以在单元格上调用_set_number_format()
方法:
cell._set_number_format('MM/DD/YY HH:MM')
您还可以通过为单元格设置ws._styles
来定义样式并重复使用它:
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
经过测试 - 为我工作过。
答案 3 :(得分:1)
我相信您需要在要格式化的单元格上设置openpyxl.styles.Style
。
查看documentation here,这样的事情应该有效:
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
<强>更新强> 不再使用样式类,因为解决方案请参考此answer。
答案 4 :(得分:1)
对于openpyxl 2.3.4,无法导入NumberFormat,但此代码用于设置样式:
from openpyxl.styles import Style
…
date_style = Style(number_format="DD/MM/YYYY HH:MM:MM")
ws['A1'].style = date_style
答案 5 :(得分:0)
我发现这可行。尽管使用了number_format,但是它似乎可以识别放入excel wb中指定的日期格式。
import datetime
date = datetime.date(2020, 2, 24) # python datetime format is yyyy mm dd
ws.cell(row=[row_ref], column=[col_ref], value=date)
ws.cell(row=[row_ref], column=[col_ref]).number_format = 'dd/mm/yy'
答案 6 :(得分:0)
from openpyxl import load_workbook
from openpyxl.styles import NamedStyle
xlsx_file = args.xlsx_file.name
# openning:
wb = load_workbook(filename = xlsx_file)
# create date style:
date_style = NamedStyle(name='date_style', number_format='DD.MM.YYYY HH:MM:MM')
# apply the style to the column H of the default sheet:
ws = wb.active
for row in ws[2:ws.max_row]: # skip the header
cell = row[7] # column H
cell.style = date_style
# saving:
wb.save(xlsx_file)
编辑:以上内容对我有效,但在我的同事计算机上不起作用。将单元格转换为固定的字符串:
import datetime
from openpyxl import load_workbook
from openpyxl.styles import Alignment
xlsx_file = 'file.xlsx'
date_format = '%Y-%b-%d'
# openning:
wb = load_workbook(filename = xlsx_file)
# we also center align that column:
alignment = Alignment(horizontal='center')
# apply python date format to column H of the default sheet, and convert the column to Excel text:
ws = wb.active
for row in ws[2:ws.max_row]: # skip the header
cell = row[7] # column H
if isinstance(cell.value, datetime.datetime):
cell.value = cell.value.strftime(date_format)
cell.alignment = alignment
# saving:
wb.save(xlsx_file)
同样包含在脚本中:
#!/usr/bin/env python3
import argparse
import datetime
from openpyxl import load_workbook
from openpyxl.styles import Alignment
# ==============
## parsing args:
desc="""
Applies python date format to a given column of the xlsx file (default sheet) and converts the column to a Excel text format.
Dependencies:
pip3 install --user --upgrade openpyxl
"""
parser = argparse.ArgumentParser(description=desc, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--version', action='version', version='%(prog)s 0.01')
parser.add_argument('-f', '--file',
help = "xlsx file",
dest = 'xlsx_file',
type = argparse.FileType('r'),
)
parser.add_argument('-c', '--column',
help = "column (starting from A) (default to %(default)s)",
dest = 'column',
type = str,
default = "A",
)
parser.add_argument('-d', '--date-format',
help = "date format to use, e.g. %%d.%%m.%%Y (default to %(default)s)",
dest = 'date_format',
type = str,
default = '%Y-%b-%d',
)
args = parser.parse_args()
# =========
## program:
xlsx_file = args.xlsx_file.name
column_number = sum(
[ ord(char) - 97 + i*26 for i,char in enumerate(
list( args.column.lower() )
) ]
)
# openning:
wb = load_workbook(filename = xlsx_file)
# we also center align that column:
alignment = Alignment(horizontal='center')
# apply python date format to a given column of the default sheet, and convert the column to Excel text:
ws = wb.active
for row in ws[2:ws.max_row]: # skip the header
cell = row[column_number]
if isinstance(cell.value, datetime.datetime):
cell.value = cell.value.strftime(args.date_format)
cell.alignment = alignment
# saving:
wb.save(xlsx_file)