0

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
newCoder
  • 11
  • 1
  • That is a problem indeed, do you know if the day's always first? Otherwise how can you know if 1/4/2000 is 1st of April or 4th of Jan? – Celius Stingher Nov 07 '20 at 22:02
  • Does this answer your question? [How to parse string dates with 2-digit year?](https://stackoverflow.com/questions/16600548/how-to-parse-string-dates-with-2-digit-year) – FObersteiner Nov 07 '20 at 22:23

1 Answers1

3

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)]
Mark
  • 90,562
  • 7
  • 108
  • 148