gpt4 book ai didi

python - 将字符串转换为日期时间 - 'Feb' 月未解析

转载 作者:太空狗 更新时间:2023-10-30 02:29:50 26 4
gpt4 key购买 nike

我有一系列如下格式的字符串对象:

lcd['dates'] = ['Sep-2014', 'Feb-2014', 'Apr-2014', 'Oct-2013', 'Oct-2014',...]

我正在尝试将它们转换为日期时间格式(四舍五入为天),如下所示:

lcd['new dates'] = [pd.to_datetime(j, unit = "D",exact=False) for j in lcd.dates]

这似乎适用于除 2 月以外的所有月份:

In: lcd['new_dates'].unique():

Out:Timestamp('2013-05-29 00:00:00'), Timestamp('2015-03-29 00:00:00'),
Timestamp('2012-06-29 00:00:00'), 'Feb-2015',
Timestamp('2012-12-29 00:00:00'), Timestamp('2014-07-29 00:00:00'),
Timestamp('2014-09-29 00:00:00'), 'Feb-2014',...

我被难住了。

最佳答案

您可以这样指定格式:

import pandas as pd

lcd = ['Sep-2014', 'Feb-2014', 'Feb-2015', 'Apr-2014', 'Oct-2013', 'Oct-2014',]
lcd = [pd.to_datetime(j, unit = "D", format='%b-%Y') for j in lcd]
print lcd

打印:

[Timestamp('2014-09-01 00:00:00'), Timestamp('2014-02-01 00:00:00'), Timestamp('2015-02-01 00:00:00'), Timestamp('2014-04-01 00:00:00'), Timestamp('2013-10-01 00:00:00'), Timestamp('2014-10-01 00:00:00')]

还可以查看 datetime 的所有格式选项.

关于python - 将字符串转换为日期时间 - 'Feb' 月未解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30539982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com