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.

2
  • 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? Commented Nov 7, 2020 at 22:02
  • Does this answer your question? How to parse string dates with 2-digit year? Commented Nov 7, 2020 at 22:23

1 Answer 1

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)]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.