【问题标题】:How can I convert this string '2012-07-06T21:00:00.000Z' To datetime format to calculate the age [duplicate]如何将此字符串'2012-07-06T21:00:00.000Z'转换为日期时间格式以计算年龄[重复]
【发布时间】: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


【解决方案1】:

怎么样:

import pandas as pd

df['birth_date'] = df['birth_date'].astype('datetime64[ns, UTC]')
df['age'] = pd.Timestamp.utcnow() - df['birth_date']
df['age_str'] = df['age'].apply(lambda td: f'{td.days//365}y{int((td.days/365 - td.days//365)*365/30)}m')

在这里,您首先将birth_date 列转换为datetime dtype,然后使用当前时间计算时间增量。 最后,您从天数计算年数和月数。

【讨论】:

    猜你喜欢
    • 2019-11-10
    • 1970-01-01
    • 2020-03-07
    • 2020-05-01
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    相关资源
    最近更新 更多