【发布时间】:2020-11-01 07:03:05
【问题描述】:
所以我有一个数据框,其中出生日期写为字符串'2012-07-06T21:00:00.000Z'(示例)。
我想据此计算用户的年龄。请注意,这是一个字符串,我想我需要它是 datetime 才能计算它。
非常感谢
我的代码(Python):
def calculate_age(born):
born = datetime.strptime(born, "%Y-%m-%d'T'%H:%M:%S.%f%Z").date()
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
df['age'] = df['birth_date'].apply(calculate_age)
【问题讨论】:
-
看看库
dateparser。如果您没有预定义的格式,这会有所帮助
标签: python datetime type-conversion