associação pythonbrasil[11] django zope/plone planet Início Logado como (Entrar)

DateDiff

Receita: DateDiff

Função pra calcular a diferença entre duas datas....

Código

   1 """Function to calculate the difference between two dates."""
   2 __revision__ = 0.1
   3 
   4 def date_diff(start_date, end_date):
   5     """
   6     Function to get the days diference between
   7     two dates.
   8     The date format should be in:
   9         Year-Month-Day ,format
  10     Ex:
  11         "2004-11-05"
  12         
  13     Ex2:
  14         
  15         print date_diff("2004-11-05","2004-12-05")    
  16     
  17     * If the date is not in this format it wont work.
  18     """
  19 
  20     #===========================================================================
  21     # Import
  22     #===========================================================================
  23     from datetime import date
  24     
  25     #===========================================================================
  26     # Process the date.
  27     #===========================================================================
  28     # TODO: Let this code more pythonic
  29     start_splited = start_date.split('-')
  30     end_splited = end_date.split('-')
  31     start = date(int(start_splited[0]),  int(start_splited[1]),  \
  32     int(start_splited[2]))
  33     end = date(int(end_splited[0]),  int(end_splited[1]),  int(end_splited[2]))
  34     
  35     #===========================================================================
  36     # Calculates and returns the diference.
  37     #===========================================================================
  38     return (end-start).days

Exemplo de uso

* Exemplo de uso no comentário do código acima.

Volta para CookBook.


ralobao (ralobaoAROBAgmail.com)