我正在研究时间序列,因此我想将对象类型转换为日期时间。我有一个像这样的数据框:
trxyear trxmonth
0 2014 JUL-13
1 2014 JUL-13
2 2014 JUL-13
3 2014 JUL-13
4 2014 JUL-13
... ... ...
46394 2023 SEP-22
46395 2023 SEP-22
46396 2023 SEP-22
46397 2023 SEP-22
46398 2023 SEP-22
我想将 trxmonth
转换为日期时间,以便我可以应用时间序列。但是当我使用此代码进行转换时
代码:
from dateutil import parser
print(parser.parse("JUL-13"))
输出:
2022-07-13 00:00:00
但它可以将 July 2013
转换为 13 July 2022
。
代码:
print(parser.parse("01-JUL-13") )
输出:
2013-07-01 00:00:00
当我使用此代码时,它可以正确转换,但我的数据不是这种格式。
只是我想转换 JUL-13
--> 01-07-2013
最佳答案
使用to_datetime
使用 format
参数:
df['trxmonth'] = pd.to_datetime(df['trxmonth'], format='%b-%y')
print (df)
trxyear trxmonth
0 2014 2013-07-01
1 2014 2013-07-01
2 2014 2013-07-01
3 2014 2013-07-01
4 2014 2013-07-01
46394 2023 2022-09-01
46395 2023 2022-09-01
46396 2023 2022-09-01
46397 2023 2022-09-01
46398 2023 2022-09-01
关于python - 在时间序列预测中将对象类型转换为日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73725847/