How to format date string via multiple formats in python

前端 未结 4 1896
北恋
北恋 2020-11-27 04:48

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

相关标签:
4条回答
  • 2020-11-27 05:20

    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')
    
    0 讨论(0)
  • 2020-11-27 05:30

    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 --> ): ")
    
    0 讨论(0)
  • 2020-11-27 05:39

    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.

    0 讨论(0)
  • 2020-11-27 05:42
    >>> 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.

    0 讨论(0)
提交回复
热议问题