将日期字符串转换为熊猫中的另一种格式日期字符串

时间:2020-10-14 09:32:37

标签: python python-3.x pandas datetime timestamp

我有一个数据框,其中有两列名为created_atupdated_at的列,它们是格式为%Y-%m-%dT%H:%M:%S+0000的日期字符串。我需要将它们转换为'%Y-%m-%d %H:%M:%S'。我已经尝试了以下方法,但是没有用:

data[['created_at', 'updated_at']] = pd.to_datetime(
                data[['created_at', 'updated_at']], format='%Y-%m-%dT%H:%M:%S+0000').dt.strftime('%Y-%m-%d %H:%M:%S')

data[['created_at', 'updated_at']] = data[['created_at', 'updated_at']].apply(
                lambda x: datetime.datetime.strptime(x, '%Y-%m-%dT%H:%M:%S+0000').strftime('%Y-%m-%d %H:%M:%S'))

data[['created_at', 'updated_at']] = pd.to_datetime(
                data[['created_at', 'updated_at']], infer_datetime_format=True, utc=True)

我该如何解决?谢谢

1 个答案:

答案 0 :(得分:2)

使用:

f = lambda x: pd.to_datetime(x, utc=True).dt.strftime('%Y-%m-%d %H:%M:%S')
data[['created_at', 'updated_at']] = data[['created_at', 'updated_at']].apply(f)