首页 > 解决方案 > 我在数据框中有一个日期列。我想在该列中更改日期的格式

问题描述

我在数据集中有一个日期列,其中日期类似于“Apr-12”、“Jan-12”格式。我想将格式更改为 04-2012,01-2012。我正在寻找可以做到这一点的功能。

标签: pythonpandas

解决方案


我想我认识一个同名的人。这里的笑话是解决您问题的方法。我们确实有一个名为strptime()的内置函数,因此它会占用字符串,然后转换为您想要的格式。

  1. 您需要先导入 datetime,因为它是 python 的 datetime 包的一部分。不需要安装任何东西,只需导入它。
  2. 然后这样工作:datetime.strptime(your_string, format_you_want)
# You can also do this, from datetime import * (this imports all the functions of datetime)
from datetime import datetime
str = 'Apr-12'
date_object = datetime.strptime(str, '%m-%Y')
print(date_object)

我希望这对你有用。快乐编码:)


推荐阅读