Anshul Goyal
Anshul Goyal

Reputation: 76847

ValueError parsing a date from string

I'm parsing a date from a string like below:

In [26]: import datetime

In [27]: datetime.datetime.strptime("2017-02-17", "%y-%m-%d")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-27-800b4156e406> in <module>()
----> 1 datetime.datetime.strptime("2017-02-17", "%y-%m-%d")

/usr/lib/python2.7/_strptime.py in _strptime(data_string, format)
    323     if not found:
    324         raise ValueError("time data %r does not match format %r" %
--> 325                          (data_string, format))
    326     if len(data_string) != found.end():
    327         raise ValueError("unconverted data remains: %s" %

ValueError: time data '2017-02-17' does not match format '%y-%m-%d'

However, I'm missing something obvious and for the life of me can't figure what is it. Can someone help me parse it?

Upvotes: 0

Views: 88

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140168

%y is the 2-digit legacy format for years. You need %Y

datetime.datetime.strptime("2017-02-17", "%Y-%m-%d")

result:

datetime.datetime(2017, 2, 17, 0, 0)

Upvotes: 2

Related Questions