Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

vigiboard / vigiboard / lib / dateformat.py @ b373a5de

History | View | Annotate | Download (1.63 KB)

1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2006-2011 CS-SI
3
# License: GNU GPL v2 <http://www.gnu.org/licenses/gpl-2.0.html>
4

    
5
"""
6
Validateur et convertisseur de dates selon un format.
7
"""
8
from formencode.api import FancyValidator, Invalid
9
from datetime import datetime
10

    
11
from pylons.i18n import ugettext as _, lazy_ugettext as l_
12

    
13
class DateFormatConverter(FancyValidator):
14
    """
15
    Valide une date selon un format identique à ceux
16
    acceptés par la fonction strptime().
17
    """
18
    messages = {
19
        'invalid': 'Invalid value',
20
    }
21

    
22
    def _to_python(self, value, state):
23
        if not isinstance(value, basestring):
24
            raise Invalid(self.message('invalid', state), value, state)
25

    
26
        str_date = value.lower()
27
        if isinstance(str_date, unicode):
28
            str_date = str_date.encode('utf-8')
29

    
30
        try:
31
            # TRANSLATORS: Format de date et heure Python/JavaScript.
32
            # TRANSLATORS: http://www.dynarch.com/static/jscalendar-1.0/doc/html/reference.html#node_sec_5.3.5
33
            # TRANSLATORS: http://docs.python.org/release/2.5/lib/module-time.html
34
            date = datetime.strptime(str_date, _('%Y-%m-%d %I:%M:%S %p').encode('utf8'))
35
        except ValueError, e:
36
            raise Invalid(self.message('invalid', state), value, state)
37
        return date
38

    
39
    def _from_python(self, value, state):
40
        if not isinstance(value, datetime):
41
            raise Invalid(self.message('invalid', state), value, state)
42

    
43
        # Même format que pour _to_python.
44
        return datetime.strftime(
45
                    value,
46
                    _('%Y-%m-%d %I:%M:%S %p').encode('utf8')
47
                ).decode('utf-8')