将 Pandas 列转换为 DateTime II

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32583256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:53:44  来源:igfitidea点击:

Convert Pandas Column to DateTime II

pythondatetimepandas

提问by Robert

I am trying to convert a column of DateTime Strings into a Pandas-comprehensible Datetime Format. Of course I already googled and tried several solutions. Convert Pandas Column to DateTime

我正在尝试将一列日期时间字符串转换为 Pandas 可理解的日期时间格式。当然,我已经用谷歌搜索并尝试了几种解决方案。 将 Pandas 列转换为日期时间

This one appeared the most encouraging for me but both recommended ways did not work for my dataset. The details: Dataset name: co,

这对我来说似乎是最令人鼓舞的,但两种推荐的方法都不适用于我的数据集。详细信息:数据集名称:co,

Column: index-column,

列:索引列,

Format: 15.07.2015 24:00 with no more blancs before or after.

格式:15.07.2015 24:00 之前或之后没有更多的空白。

My efforts:

我的努力:

co['newdate'] = pd.to_datetime(co.index, format='%d.%m.%Y %H:%M')

The next one I tried after I transformed the Index-col to a "normal" column named "Datum"

在将 Index-col 转换为名为“Datum”的“正常”列后,我尝试了下一个

co['newdate'] = co['Datum'].apply(lambda x: dt.datetime.strptime(x,'%d.%m.%Y %H:%M'))

The error: time data '15.07.2015 24:00' does not match format '%d.%m.%Y %H:%M'

错误:时间数据 '15.07.2015 24:00' 与格式 '%d.%m.%Y %H:%M' 不匹配

this error occurs in both solutions. Anyone an idea?

两种解决方案都会出现此错误。任何人的想法?

回答by EdChum

Your format string is correct but your data is not, 24is not a valid hour component hence the error:

您的格式字符串正确,但您的数据不正确,24不是有效的小时组件,因此出现错误:

In [138]:

pd.to_datetime('15.07.2015 24:00', format = '%d.%m.%Y %H:%M')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\tseries\tools.py in _convert_listlike(arg, box, format)
    329             try:
--> 330                 values, tz = tslib.datetime_to_datetime64(arg)
    331                 return DatetimeIndex._simple_new(values, None, tz=tz)

pandas\tslib.pyx in pandas.tslib.datetime_to_datetime64 (pandas\tslib.c:23823)()

TypeError: Unrecognized value type: <class 'str'>

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-138-1546fb6950f0> in <module>()
----> 1 pd.to_datetime('15.07.2015 24:00', format = '%d.%m.%Y %H:%M')

C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\tseries\tools.py in to_datetime(arg, errors, dayfirst, utc, box, format, exact, coerce, unit, infer_datetime_format)
    343         return _convert_listlike(arg, box, format)
    344 
--> 345     return _convert_listlike(np.array([ arg ]), box, format)[0]
    346 
    347 class DateParseError(ValueError):

C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\tseries\tools.py in _convert_listlike(arg, box, format)
    331                 return DatetimeIndex._simple_new(values, None, tz=tz)
    332             except (ValueError, TypeError):
--> 333                 raise e
    334 
    335     if arg is None:

C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\tseries\tools.py in _convert_listlike(arg, box, format)
    305                     try:
    306                         result = tslib.array_strptime(
--> 307                             arg, format, exact=exact, coerce=coerce
    308                         )
    309                     except (tslib.OutOfBoundsDatetime):

pandas\tslib.pyx in pandas.tslib.array_strptime (pandas\tslib.c:39900)()

ValueError: time data '15.07.2015 24:00' does not match format '%d.%m.%Y %H:%M' (match)

whilst 23:59will parse fine

虽然23:59会解析得很好

In [139]:
pd.to_datetime('15.07.2015 23:59', format = '%d.%m.%Y %H:%M')

Out[139]:
Timestamp('2015-07-15 23:59:00')

You need to replace 24with 0in order for this to parse:

您需要替换24with0以便解析:

In [140]:
pd.to_datetime('15.07.2015 00:00', format = '%d.%m.%Y %H:%M')

Out[140]:
Timestamp('2015-07-15 00:00:00')

So what you can do is call the vectorised str.replaceto fix these errant hour values:

所以你可以做的是调用矢量化str.replace来修复这些错误的小时值:

In [144]:
df = pd.DataFrame({'date':['15.07.2015 24:00']})
print(df)
df['date'] = df['date'].str.replace('24:','00:')
print(df)
pd.to_datetime(df['date'], format = '%d.%m.%Y %H:%M')

               date
0  15.07.2015 24:00
               date
0  15.07.2015 00:00
Out[144]:
0   2015-07-15
Name: date, dtype: datetime64[ns]

So in your case you can do:

所以在你的情况下,你可以这样做:

co.index = co.index.str.replace('24:','00:')

and then convert as before

然后像以前一样转换