Excel wont recognize date using openpyxl

北慕城南 提交于 2021-01-27 06:40:18

问题


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'

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


回答1:


My mistake was assuming the line below created a date.

date = datetime.datetime.fromtimestamp(int(startdate)).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()

Now excel recognizes it as a date.

Hopefully this helps someone in the future.



来源:https://stackoverflow.com/questions/43947652/excel-wont-recognize-date-using-openpyxl

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