Search code examples
pythondatetimestrptime

Bad directive in format '%' datetime.strptime


When i try to change format of str to date time , i face ValueError,

this may simple problem but cant find solution on google or stackoverflow too , i found some solution about 'z' is bad directive in format but not '%' one

current_session.date = datetime.strptime('2019-06-16 00:02', '%Y-%B-%d% %H:%M')



Traceback (most recent call last):
  File "/home/rambod/PycharmProjects/mailWatcher/smtpINWatcher.py", line 92, in <module>
    current_session.date = datetime.strptime('2019-06-16 00:02', '%Y-%B-%d% %H:%M')
  File "/usr/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/usr/lib/python3.7/_strptime.py", line 351, in _strptime
    (bad_directive, format)) from None
ValueError: '%' is a bad directive in format '%Y-%B-%d% %H:%M'

Solution

  • Try:

    current_session.date = datetime.strptime('2019-06-16 00:02', '%Y-%B-%d %H:%M')
    

    (Note the removal of the extra % after d.)

    EDIT:
    The above will still be incorrect because %B is the full month name, so you should instead try:

    current_session.date = datetime.strptime('2019-06-16 00:02', '%Y-%m-%d %H:%M')