2012-04-03 13 views
15

Sto costruendo una sorta di calendario web appIn python, come verificare se una data è valida?

ho predisposto il seguente modulo HTML

<form action='/event' method='post'> 
Year ("yyyy"): <input type='text' name='year' /> 
Month ("mm"): <input type='text' name='month' /> 
Day ("dd"): <input type='text' name='day' /> 
Hour ("hh"): <input type='text' name='hour' /> 
Description: <input type='text' name='info' /> 
      <input type='submit' name='submit' value='Submit'/> 
</form> 

L'input da parte dell'utente viene poi submited nel server un cherrypy

Sono chiedendo, c'è un modo per verificare se la data inserita dall'utente è una data valida?

Ovviamente potrei scrivere un sacco di istruzioni if, ma ci sono funzioni incorporate in grado di verificarlo?

Grazie

+0

correlati: [Come faccio a convalidare una data stringa di formato in Python?] (Http://stackoverflow.com/q/16870663) – kenorb

risposta

18

si potrebbe provare a fare

import datetime 
datetime.datetime(year=year,month=month,day=day,hour=hour) 

che eliminerà quarantina come mesi> 12, ore> 23, leapdays inesistenti (mese = 2 ha massimo di 28 su anni non bisestili, 29 altrimenti , altri mesi hanno un massimo di 30 o 31 giorni) (genera eccezione ValueError in caso di errore)

Inoltre, si potrebbe provare a confrontarlo con alcuni limiti superiori/inferiori di sanità. es .:

datetime.date(year=2000, month=1,day=1) < datetime.datetime(year=year,month=month,day=day,hour=hour) <= datetime.datetime.now() 

I relativi limiti di integrità superiore e inferiore dipende dalle esigenze.

edit: ricordate che questa non gestisce certe datetimes cose che potrebbero non essere valide per la vostra applicazione

3

Usa datetime

ad es.

>>> from datetime import datetime 
>>> print datetime(2008,12,2) 
2008-12-02 00:00:00 
>>> print datetime(2008,13,2) 

Traceback (most recent call last): 
    File "<pyshell#4>", line 1, in <module> 
    print datetime(2008,13,2) 
ValueError: month must be in 1..12 
+0

Ma non vorrei che mi danno un messaggio di errore? e fare in modo che tutto si arresti? Speravo se esista una funzione che per esempio, restituisce 1 se è una data valida e restituisce 0 se non è valida. Quindi posso chiedere all'utente di reinserire la data nella pagina web. – Synia

+1

Oppure potresti 'provare ... tranne' e rilevare l'errore. Quindi puoi fare ciò che vuoi, passare silenziosamente l'errore se lo desideri. – jamylak

+1

vedere http://docs.python.org/tutorial/errors.html#handling-exceptions –

21

Puoi provare a utilizzare datetime e gestire le eccezioni (min compleanno, feste, dalle ore di funzionamento, ecc.) decidere valida attività di/non valida: Esempio: http://codepad.org/XRSYeIJJ

import datetime 
correctDate = None 
try: 
    newDate = datetime.datetime(2008,11,42) 
    correctDate = True 
except ValueError: 
    correctDate = False 
print(str(correctDate)) 
-1

Quindi, ecco la mia soluzione hacky per correggere le date non valide fornite. Ciò presuppone che l'utente stia inviando da un modulo html generico che fornisce i giorni 1-31 come opzioni. Il problema principale è che forniscono agli utenti un giorno che non esiste per il mese (ex 31 settembre)

def sane_date(year, month, day): 
    # Calculate the last date of the given month 
    nextmonth = datetime.date(year, month, 1) + datetime.timedelta(days=35) 
    lastday = nextmonth.replace(day=1) - datetime.timedelta(days=1) 
    return datetime.date(year, month, min(day, lastday.day)) 

class tests(unittest.TestCase): 

    def test_sane_date(self): 
     """ Test our sane_date() method""" 
     self.assertEquals(sane_date(2000,9,31), datetime.date(2000,9,30)) 
     self.assertEquals(sane_date(2000,2,31), datetime.date(2000,2,29)) 
     self.assertEquals(sane_date(2000,1,15), datetime.date(2000,1,15)) 
1

Ecco una soluzione che utilizza il tempo.

import time 
def is_date_valid(year, month, day): 
    this_date = '%d/%d/%d' % (month, day, year) 
    try: 
     time.strptime(this_date, '%m/%d/%Y') 
    except ValueError: 
     return False 
    else: 
     return True 
+1

perché dovresti farlo invece di 'data (anno, mese, giorno)'? – jfs

1

Puoi provare a utilizzare datetime e gestire le eccezioni di decidere valida/data non valida:

import datetime 

def check_date(year, month, day): 
    correctDate = None 
    try: 
     newDate = datetime.datetime(year, month, day) 
     correctDate = True 
    except ValueError: 
     correctDate = False 
    return correctDate 

#handles obvious problems 
print(str(check_date(2008,11,42))) 

#handles leap days 
print(str(check_date(2016,2,29))) 
print(str(check_date(2017,2,29))) 

#handles also standard month length 
print(str(check_date(2016,3,31))) 
print(str(check_date(2016,4,31))) 

gives

False 
True 
False 
True 
False 

Questo è il miglioramento della an answer by DhruvPathak e rende più senso come modifica ma è stato rifiutato come "This edit was intended to address the author of the post and makes no sense as an edit. It should have been written as a comment or an answer."

Problemi correlati