2014-05-10 19 views
11

Ho tre formati di data: YYYY-MM-DD, DD.MM.YYYY, DD/MM/YYYY.Come formattare la stringa di data tramite più formati in python

È possibile convalidare e analizzare stringhe come 2014-05-18 o 18.5.2014 o 18/05/2019?

+1

Hai guardato [dateutil] (https://labix.org/python- dateutil) - in mancanza di questo - basta provare 'strptime'ing ogni 3 a sua volta, per vedere se funzionano, altrimenti non riuscire ... –

+1

Grazie per la comment.I vuole usare python puro senza librerie di terze parti –

risposta

46

provare ogni formato e vedere se funziona:

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') 
+1

l'ultimo è'% y'. Dovrebbe essere '% Y'. –

+1

@Vaibhav buon punto - a cura - grazie. –

0

Pure pitone:

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

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

Controllare datetime.strptime() Documentazione formato per più stringhe di formato.

+0

La soluzione deve essere espansa per utilizzare tutti i formati di data e spiegare come scegliere quale si adatta. –

+0

@HansQuando hai ragione, ma la risposta sopra risponde già correttamente alla domanda e non c'è nulla da aggiungere ad essa. –

+0

Sì, è difficile migliorare su @Jon Clements. –

6
>>> import dateutil.parser 
>>> dateutil.parser.parse(date_string) 

Questo dovrebbe occuparsi della maggior parte dei formati di data standard in Python 2.7+. Se hai davvero formati di data super personalizzati, puoi sempre ricorrere a quello menzionato da Jon Clements.

0

Questo in realtà un problema che stavo affrontando e questo come mi sono avvicinato, il mio scopo principale era quello dei separatori di data

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 -->): ") 
Problemi correlati