Rambod
Rambod

Reputation: 2703

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'

Upvotes: 3

Views: 7022

Answers (3)

frankegoesdown
frankegoesdown

Reputation: 1924

%B is for Month as locale’s full name. like

January, February, …, December (en_US); Januar, Februar, …, Dezember (de_DE)

Your example

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

In [26]: date                                                                                                                                                                                 
Out[26]: datetime.datetime(2019, 6, 16, 0, 2)

https://docs.python.org/3/library/datetime.html

Upvotes: 3

vekerdyb
vekerdyb

Reputation: 1263

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')

Upvotes: 3

Oleh Rybalchenko
Oleh Rybalchenko

Reputation: 8059

You have an extra % sign after %d, that's the reason. However, the pattern is still wrong for the string you're trying to parse - %B stands for full month name, not number. I suppose %m is what you need:

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

Here's a good description on how strftime works. Or check Python docs for more detailed explanation.

Upvotes: 2

Related Questions