Python: Parse String as Date with Formatting
Question: A user can input a string and the string contains a date in the following
formats `MM/DD/YY` or `MM/DD/YYYY`. Is there an efficient way to pull the date
from the string? I was thinking of using RegEx for `\d+\/\d+\/\d+`. I also
want the ability to be able to sort the dates. I.e. if the strings contain
`8/17/15` and `08/16/2015`, it would list the 8/16 date first and then 8/17


Answer: you could also try strptime:

    
    
    import time
    
    dates = ('08/17/15', '8/16/2015')
    
    for date in dates:
        print(date)
        ret = None
        try:
            ret = time.strptime(date, "%m/%d/%Y")
        except ValueError:
            ret = time.strptime(date, "%m/%d/%y")
        print(ret)
    

* * *

**UPDATE**

update after comments:

this way you will get a valid date back or `None` if the date can not be
parsed:

    
    
    import time
    
    dates = ('08/17/15', '8/16/2015', '02/31/15')
    
    for date in dates:
        print(date)
        ret = None
        try:
            ret = time.strptime(date, "%m/%d/%Y")
        except ValueError:
            try:
                ret = time.strptime(date, "%m/%d/%y")
            except ValueError:
                pass
        print(ret)
    

* * *

**UPDATE** **2**

one more update after the comments about the requirements.

this is a version (it only takes care of the dates; not the text before/after.
but using the regex group this can easily be extracted):

    
    
    import re
    import time
    
    dates = ('foo 1 08/17/15', '8/16/2015 bar 2', 'foo 3 02/31/15 bar 4')
    
    for date in dates:
        print(date)
        match = re.search('(?P<date>[0-9]+/[0-9]+/[0-9]+)', date)
        date_str = match.group('date')
        ret = None
        try:
            ret = time.strptime(date_str, "%m/%d/%Y")
        except ValueError:
            try:
                ret = time.strptime(date_str, "%m/%d/%y")
            except ValueError:
                pass
        print(ret)
    

