Tommy Lees
Tommy Lees

Reputation: 1373

Parsing non-zero padded 12-hour datetime format in Python

I am trying to parse a date-time string in python. It is a non-zero padded 12-hour format (%I) with a trailing string denoting [AM, PM] (%p)

I cannot interpret the following error messages. How is the string incorrectly formatted?

With Datetime .strptime()

from datetime import datetime 

datetime.strptime("3/31/21 1:50PM", '%d/%m/%y %I:%M%p')

Returns:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-41-8f0bfdfcb876> in <module>
----> 1 datetime.strptime("3/31/21 1:50PM", '%d/%m/%y %I:%M%p')

~/miniconda3/envs/metpy/lib/python3.9/_strptime.py in _strptime_datetime(cls, data_string, format)
    566     """Return a class cls instance based on the input string and the
    567     format string."""
--> 568     tt, fraction, gmtoff_fraction = _strptime(data_string, format)
    569     tzname, gmtoff = tt[-2:]
    570     args = tt[:6] + (fraction,)

~/miniconda3/envs/metpy/lib/python3.9/_strptime.py in _strptime(data_string, format)
    347     found = format_regex.match(data_string)
    348     if not found:
--> 349         raise ValueError("time data %r does not match format %r" %
    350                          (data_string, format))
    351     if len(data_string) != found.end():

ValueError: time data '3/31/21 1:50PM' does not match format '%d/%m/%y %I:%M%p'

With Pandas to_datetime()

import pandas as pd 

pd.to_datetime("3/31/21 1:50PM", format='%d/%m/%y %I:%M%p')

Returns

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~/miniconda3/envs/metpy/lib/python3.9/site-packages/pandas/core/tools/datetimes.py in _convert_listlike_datetimes(arg, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact)
    455             try:
--> 456                 values, tz = conversion.datetime_to_datetime64(arg)
    457                 dta = DatetimeArray(values, dtype=tz_to_dtype(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-43-72b4542d7532> in <module>
----> 1 pd.to_datetime("3/31/21 1:50PM", format='%d/%m/%y %I:%M%p')

~/miniconda3/envs/metpy/lib/python3.9/site-packages/pandas/core/tools/datetimes.py in to_datetime(arg, errors, dayfirst, yearfirst, utc, format, exact, unit, infer_datetime_format, origin, cache)
    830             result = convert_listlike(arg, format)
    831     else:
--> 832         result = convert_listlike(np.array([arg]), format)[0]
    833
    834     return result

~/miniconda3/envs/metpy/lib/python3.9/site-packages/pandas/core/tools/datetimes.py in _convert_listlike_datetimes(arg, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact)
    458                 return DatetimeIndex._simple_new(dta, name=name)
    459             except (ValueError, TypeError):
--> 460                 raise e
    461
    462     if result is None:

~/miniconda3/envs/metpy/lib/python3.9/site-packages/pandas/core/tools/datetimes.py in _convert_listlike_datetimes(arg, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact)
    421             if result is None:
    422                 try:
--> 423                     result, timezones = array_strptime(
    424                         arg, format, exact=exact, errors=errors
    425                     )

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

ValueError: time data '3/31/21 1:50PM' does not match format '%d/%m/%y %I:%M%p' (match)

Using strftime reference

When I try using the non-zero padded information I get a bad directive in format error

datetime.strptime("3/31/21 1:50PM", '%-d/%m/%y %-I:%M%p')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-44-84bcd95d0fd5> in <module>
----> 1 datetime.strptime("3/31/21 1:50PM", '%d/%m/%y %-I:%M%p')

~/miniconda3/envs/metpy/lib/python3.9/_strptime.py in _strptime_datetime(cls, data_string, format)
    566     """Return a class cls instance based on the input string and the
    567     format string."""
--> 568     tt, fraction, gmtoff_fraction = _strptime(data_string, format)
    569     tzname, gmtoff = tt[-2:]
    570     args = tt[:6] + (fraction,)

~/miniconda3/envs/metpy/lib/python3.9/_strptime.py in _strptime(data_string, format)
    339                     bad_directive = "%"
    340                 del err
--> 341                 raise ValueError("'%s' is a bad directive in format '%s'" %
    342                                     (bad_directive, format)) from None
    343             # IndexError only occurs when the format string is "%"

ValueError: '-' is a bad directive in format '%-d/%m/%y %-I:%M%p'

Upvotes: 1

Views: 471

Answers (1)

norie
norie

Reputation: 9857

You have day and month the wrong way round.

This should work.

from datetime import datetime 

datetime.strptime("3/31/21 1:50PM", '%m/%d/%y %I:%M%p')

Upvotes: 2

Related Questions