Search code examples
python-3.xpandasformatstrftimestring-to-datetime

pd.to_datetime format argument is rejected


I can not understand this exception:

date = '01/01 24:00:00'
pd.to_datetime(date, format = '%m/%d %H:%M:%S')

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\Anaconda3\envs\tf2\lib\site-packages\pandas\core\tools\datetimes.py in _convert_listlike_datetimes(arg, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact)
    431             try:
--> 432                 values, tz = conversion.datetime_to_datetime64(arg)
    433                 return DatetimeIndex._simple_new(values, name=name, tz=tz)

pandas\_libs\tslibs\conversion.pyx in pandas._libs.tslibs.conversion.datetime_to_datetime64()

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

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-30-1c006106355f> in <module>
----> 1 pd.to_datetime(date, format = '%m/%d %H:%M:%S')

~\Anaconda3\envs\tf2\lib\site-packages\pandas\core\tools\datetimes.py in to_datetime(arg, errors, dayfirst, yearfirst, utc, format, exact, unit, infer_datetime_format, origin, cache)
    754             result = convert_listlike(arg, format)
    755     else:
--> 756         result = convert_listlike(np.array([arg]), format)[0]
    757 
    758     return result

~\Anaconda3\envs\tf2\lib\site-packages\pandas\core\tools\datetimes.py in _convert_listlike_datetimes(arg, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact)
    433                 return DatetimeIndex._simple_new(values, name=name, tz=tz)
    434             except (ValueError, TypeError):
--> 435                 raise e
    436 
    437     if result is None:

~\Anaconda3\envs\tf2\lib\site-packages\pandas\core\tools\datetimes.py in _convert_listlike_datetimes(arg, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact)
    398                 try:
    399                     result, timezones = array_strptime(
--> 400                         arg, format, exact=exact, errors=errors
    401                     )
    402                     if "%Z" in format or "%z" in format:

pandas\_libs\tslibs\strptime.pyx in pandas._libs.tslibs.strptime.array_strptime()

ValueError: time data '01/01 24:00:00' does not match format '%m/%d %H:%M:%S' (match)

How should I remedy the code?


Solution

  • Short answer: 24 is not a valid hour.

    The hours should be in the 0-23 range, as is specified in the datetime package for the %H format directive:

    %H Hour (24-hour clock) as a zero-padded decimal number. 00, 01, …, 23

    so 24 is not in that range. If the clock is set to 01/01 24:00:00, then this is 01/02 00:00:00.