Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Datetime object of type: %B %D %Y

I have a date as:

'September 17, 2013'

And I want to convert it to:

2013-09-17

I tried this hint taken from this stackoverflow question [1]:

mydate = datetime.datetime.strptime("September 17, 2013", '%B %d, %y')

But it gives me an:

File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: 13

What should I do?

[1] convert an integer number in a date to the month name using python

like image 904
user1343318 Avatar asked Oct 02 '22 21:10

user1343318


1 Answers

Use %Y insetead of %y. the latter matches only 2 digits

%y  Year without century as a zero-padded decimal number.   00, 01, ..., 99  
%Y  Year with century as a decimal number.  1970, 1988, 2001, 2013   

Documentation here

Demo:

>>> import datetime
>>> datetime.datetime.strptime("September 17, 2013", '%B %d, %y')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: 13
>>> x = datetime.datetime.strptime("September 17, 2013", '%B %d, %Y')
>>> x
datetime.datetime(2013, 9, 17, 0, 0)
>>>

and then,

x.strftime('%Y-%m-%d')
like image 144
karthikr Avatar answered Oct 07 '22 20:10

karthikr