简体   繁体   English

在Excel电子表格中从出生日期查找年龄

[英]Finding age from Date of Birth in an excel spreadsheet

I've searched high and low, and cannot find an answer. 我搜索过高低,找不到答案。

Situation: I have a spreadsheet with dates of birth in column D. I want to calculate the age of each person and put that age in column E. I want to be able to do this for the entire spreadsheet. 情况:我在D列中有一个包含出生日期的电子表格。我想计算每个人的年龄,并将该年龄放在E列中。我希望能够在整个电子表格中做到这一点。

import openpyxl as op
import datetime

for row in range(2, ws.max_row + 1):
    ws["D"] = ws["D" + str(row)].value
    born = datetime.datetime.strptime(ws["D"], "%m/%d/%y")
    ws["E" + str(row)].value = today.year - born.year - ((today.month, today.day) < (born.month, born.day))

When I try to run that code block, I get 当我尝试运行该代码块时,我得到

`AttributeError: 'tuple' object has no attribute 'value'

which references the datetime.datetime.strptime call 引用datetime.datetime.strptime调用

The code is pretty messy at this point, because I've tried a bunch of different things and can't get it to work. 此时的代码非常混乱,因为我尝试了很多不同的事情,但无法正常工作。

The thing which you have done wrong is that you have changed the type of ws to dict in ws["D"] = ws["D" + str(row)].value . 您做错了的事情是您将ws的类型更改为ws["D"] = ws["D" + str(row)].value dict。 What you can do is as follows 您可以做的如下

import openpyxl as op
import datetime

for row in range(2, ws.max_row + 1):
    wsx["D"] = ws["D" + str(row)].value
    born = datetime.datetime.strptime(wsx["D"], "%m/%d/%y")
    ws["E" + str(row)].value = today.year - born.year - ((today.month, today.day) < (born.month, born.day))

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM