如何使用openpyxl在Excel中使用“yyyy-mm-dd hh:mm:ss”格式的datetime对象格式化单元格 [英] How to format cell with datetime object of the form 'yyyy-mm-dd hh:mm:ss' in Excel using openpyxl

查看:4231
本文介绍了如何使用openpyxl在Excel中使用“yyyy-mm-dd hh:mm:ss”格式的datetime对象格式化单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,给定:

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

Excel中的结果是将正确的日期时间写入单元格(您可以看到输入公式的位置)。但是,单元格显示格式只有MM / DD / YYYY。

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.

我需要单元格显示为6/23/2014 13:56而不是 2014\" 年6月23日。

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?

谢谢!

@alecxe这个解决方案是正确的,正是我要求的。我想要像@Woodham一样保存样式,如解决方案。不幸的是它引发了一个typeError(见注释)。任何建议?

@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?

推荐答案

我将此添加为新答案,因为我没有足够的声誉来添加评论以上。格式化单元格的最简单方法是使用.number_format =format,如下所示:

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'

这是在openpyxl中测试(2.2.2)

This is tested in openpyxl (2.2.2)

这篇关于如何使用openpyxl在Excel中使用“yyyy-mm-dd hh:mm:ss”格式的datetime对象格式化单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆