Reputation: 11
If I needed to convert a string to a date object, but the dates weren't formatted the correct way, how would I do that?
For example, if I needed to convert '3/10/18'
or '11/7/18'
to a date so I could append it to a new array, what method should I use?
I tried datetime.strptime(string, '%m/%d/%Y')
, but since the month or date isn't always 2 digits in the string, it won't convert it.
Upvotes: 0
Views: 1372
Reputation: 92440
As described in the docs:
When used with the strptime() method, the leading zero is optional for formats %d, %m, %H, %I, %M, %S, %J, %U, %W, and %V. Format %y does require a leading zero
The leading zero is optional for formats %d
and %m
. The problem is the %Y
which needs a complete year. If you want the two-character year, use %y
:
from datetime import datetime
l = ['3/10/18', '11/7/18']
[datetime.strptime(s, '%m/%d/%y') for s in l]
# [datetime.datetime(2018, 3, 10, 0, 0), datetime.datetime(2018, 11, 7, 0, 0)]
Upvotes: 3