我有一些函数可以返回节假日列表。列表如下
['30 May 2024','1 May 2024', '29 Aug 2024', '14 Aug 2024', '19 May 2024']
当我尝试做
print(pd.to_datetime(['30 May 2024','1 May 2024', '29 Aug 2024', '14 Aug 2024', '19 May 2024']))
错误
============================================================================================== RESTART: C:\Users\Bhargav\Downloads\gapi.py =============================================================================================
Traceback (most recent call last):
File "C:\Users\Bhargav\Downloads\gapi.py", line 2, in <module>
print(pd.to_datetime(['30 May 2024','1 May 2024', '29 Aug 2024', '14 Aug 2024', '19 May 2024']))
File "C:\Users\Bhargav\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\tools\datetimes.py", line 1099, in to_datetime
result = convert_listlike(argc, format)
File "C:\Users\Bhargav\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\tools\datetimes.py", line 433, in _convert_listlike_datetimes
return _array_strptime_with_fallback(arg, name, utc, format, exact, errors)
File "C:\Users\Bhargav\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\tools\datetimes.py", line 467, in _array_strptime_with_fallback
result, tz_out = array_strptime(arg, fmt, exact=exact, errors=errors, utc=utc)
File "strptime.pyx", line 501, in pandas._libs.tslibs.strptime.array_strptime
File "strptime.pyx", line 451, in pandas._libs.tslibs.strptime.array_strptime
File "strptime.pyx", line 583, in pandas._libs.tslibs.strptime._parse_with_format
ValueError: time data "29 Aug 2024" doesn't match format "%d %B %Y", at position 2. You might want to try:
- passing `format` if your strings have a consistent format;
- passing `format='ISO8601'` if your strings are all ISO8601 but not necessarily in exactly the same format;
- passing `format='mixed'`, and the format will be inferred for each element individually. You might want to use `dayfirst` alongside this.
但是但是它与这个列表完美兼容
print(pd.to_datetime(['30 Dec 2024','1 May 2024', '29 Aug 2024', '14 Aug 2024', '19 May 2024']))
我明白了
============================================================================================== RESTART: C:\Users\Bhargav\Downloads\gapi.py =============================================================================================
DatetimeIndex(['2024-12-30', '2024-05-01', '2024-08-29', '2024-08-14',
'2024-05-19'],
dtype='datetime64[ns]', freq=None)
我这里遗漏了什么吗?
问题是由于有第一个日期。May 是月份的
May
全名 (%B
) 和缩写 ( )。%b
当 pandas 尝试推断格式时,它决定使用
%d %B %Y
,这对于 来说是正确的May
,但对于 来说却不正确Aug
(它需要%b
)。 如此处所述,这是通过 完成的pandas.tseries.api.guess_datetime_format
:当将 12 月/8 月作为第一个日期时,这不会导致问题:
如果你使用
format='mixed'
或format='%d %b %Y'
,这将正常工作: