因此,我有一个数据框,它将出生日期写为字符串'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)
那么:
在这里,首先将
birth_date
列转换为datetime
数据类型,然后使用当前时间计算时间增量。 最后,从天开始计算年数和月数相关问题 更多 >
编程相关推荐