I'm trying to convert a string into a date object, I have this line of code:

datetime.strptime('01/04/2014', '%d/%m%/%y')

And I get:

ValueError: '/' is a bad directive in format '%d/%m%/%y'

I have tried changing / with other characters and also no separator but it throws up the same error (for that character)

Django 1.5.1 Python 2.7.3

Any idea what this means? Google doesn't throw up many results for the same problem.

有帮助吗?

解决方案

You have one % too many after the %m directive; %/ is not a valid directive and the ValueError tells you just that.

Use:

datetime.strptime('01/04/2014', '%d/%m/%Y')

instead, using %Y (capital Y) to parse a year with century.

Demo:

>>> datetime.strptime('01/04/2014', '%d/%m/%Y')
datetime.datetime(2014, 4, 1, 0, 0)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top