Excel 不会使用 openpyxl 识别日期 [英] Excel wont recognize date using openpyxl

查看:145
本文介绍了Excel 不会使用 openpyxl 识别日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码可以将 unix 日期转换为标准的美国日期格式.它在 excel 中正确显示,但 excel 无法将其识别为日期.

I have a piece of code that converts a unix date to standard U.S. date format. It displays properly in excel, however excel doesn't recognize it as a date.

if str(startdate).isdigit():
    startdate = int(startdate)
    date = datetime.datetime.fromtimestamp(int(startdate)).strftime('%m/%d/%Y')
    ws4.cell(row=cell.row,column=2).value = date
    ws4.cell(row=cell.row,column=2).number_format = 'MM DD YYYY'

知道如何让 excel 将其视为日期而不是文本吗?

Any idea how to get excel to see this as a date rather than text?

推荐答案

我的错误是假设下面的行创建了一个日期.

My mistake was assuming the line below created a date.

date = datetime.datetime.fromtimestamp(int(startdate)).strftime('%m/%d/%Y')

冒险进入文档后(对于菜鸟来说太可怕了.它变得更容易了吗?)我意识到 .strftime('%m/%d/%Y') 创建了一个字符串而不是一个日期.

After venturing into the docs (Scary as hell for a noob. Does it get easier?) I realized .strftime('%m/%d/%Y') created a string not a date.

我使用以下方法将该字符串转换为日期:

I converted that string to a date using:

date = datetime.datetime.strptime(date, '%m/%d/%Y').date()

现在 excel 将其识别为日期.

Now excel recognizes it as a date.

希望这对未来的人有所帮助.

Hopefully this helps someone in the future.

这篇关于Excel 不会使用 openpyxl 识别日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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