84

I have three date formats: YYYY-MM-DD, DD.MM.YYYY, DD/MM/YYYY.

Is it possible to validate and parse strings such as 2014-05-18 or 18.5.2014 or 18/05/2019?

2
  • 2
    Have you looked at dateutil - failing that - just try strptimeing each 3 in turn to see if they work, otherwise fail... Commented May 10, 2014 at 12:37
  • 1
    Thank you for the comment.I want use pure python without third party libs Commented May 10, 2014 at 12:38

5 Answers 5

184

Try each format and see if it works:

from datetime import datetime

def try_parsing_date(text):
    for fmt in ('%Y-%m-%d', '%d.%m.%Y', '%d/%m/%Y'):
        try:
            return datetime.strptime(text, fmt)
        except ValueError:
            pass
    raise ValueError('no valid date format found')
Sign up to request clarification or add additional context in comments.

1 Comment

what if we have huge data and multiple date formats, then looping through a loop is feasible in terms of time complexity? will it not be slow?
57
>>> import dateutil.parser
>>> dateutil.parser.parse(date_string)

This should take care of most of the standard date formats in Python 2.7+. If you really have super custom date formats, you can always fall back to the one mentioned by Jon Clements.

1 Comment

This works fine, but if the date formats are all known in advance, the solution by Jon Clements of trying each format and catching exceptions will likely be much faster.
2

This actually a problem i was facing and this how i approached it, my main purpose was to the date seperators

class InputRequest:
     "This class contain all inputs function that will be required in this program. "

      def __init__(self, stockTickerName = 'YHOO', stockSite='yahoo', startDate = None, 
             endDate = datetime.date.today()):

      def requestInput(self, requestType =''):
          "Fro requesting input from user"
          self.__requestInput = input(requestType)
          return self.__requestInput


def dateFormat(self, dateType=''):
    '''
        this function handles user date input
        this repeats until the correct format is supplied
        dataType: this is the type of date, eg: DOF, Date of Arriveal, etc 

    '''
    while True:
        try:
            dateString = InputRequest.requestInput(self,dateType)
            dtFormat = ('%Y/%m/%d','%Y-%m-%d','%Y.%m.%d','%Y,%m,%d','%Y\%m\%d') #you can add extra formats needed
            for i in dtFormat:
                try:
                    return datetime.datetime.strptime(dateString, i).strftime(i)
                except ValueError:
                    pass

        except ValueError:
            pass
        print('\nNo valid date format found. Try again:')
        print("Date must be seperated by either [/ - , . \] (eg: 2012/12/31 --> ): ")

Comments

1

In order to add a bit to @jon-clements already great answer,

added some verbosity on the exception raised for traceability purposes

from datetime import datetime

def try_parsing_date(possible_date, field):
    """
    Try to parse a date using several formats, warn about
    problematic value if the possible_date does not match
    any of the formats tried
    """
    for fmt in ('%Y-%m-%d', '%d/%m/%Y', '%m/%d/%Y'):
        try:
            return datetime.strptime(possible_date, fmt)
        except ValueError:
            pass
    raise ValueError(f"Non-valid date format for field {field}: '{possible_date}'")

Here, possible_date is the text that may contain a date in one of the formats, and field would be the variable or column that you are testing. This makes it easier to find the problematic value

Comments

-9

Pure python:

from datetime import datetime
my_datetime = datetime.strptime('2014-05-18', '%Y-%m-%d') 
repr(my_datetime)

>>> 'datetime.datetime(2014,5,18,0,0)'

Check datetime.strptime() format documentation for more format strings.

3 Comments

The solution should be expanded to use all date formats and explain how to choose which one fits.
@HansThen you're right, but answer above already answers the question correctly and there's nothing to add to it.
Yes, it is hard to improve upon @Jon Clements.

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.