File: rfc3339_validator.py

package info (click to toggle)
rfc3339-validator 0.1.4-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 152 kB
  • sloc: python: 113; makefile: 61
file content (51 lines) | stat: -rw-r--r-- 1,110 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# -*- coding: utf-8 -*-

__author__ = """Nicolas Aimetti"""
__email__ = 'naimetti@yahoo.com.ar'
__version__ = '0.1.4'

import re
import calendar
import six

RFC3339_REGEX_FLAGS = 0
if six.PY3:
    RFC3339_REGEX_FLAGS |= re.ASCII

RFC3339_REGEX = re.compile(r"""
    ^
    (\d{4})      # Year
    -
    (0[1-9]|1[0-2]) # Month
    -
    (\d{2})          # Day
    T
    (?:[01]\d|2[0123]) # Hours
    :
    (?:[0-5]\d)     # Minutes
    :
    (?:[0-5]\d)     # Seconds
    (?:\.\d+)?      # Secfrac
    (?:  Z                              # UTC
       | [+-](?:[01]\d|2[0123]):[0-5]\d # Offset
    )
    $
""", re.VERBOSE | RFC3339_REGEX_FLAGS)


def validate_rfc3339(date_string):
    """
    Validates dates against RFC3339 datetime format
    Leap seconds are no supported.
    """
    m = RFC3339_REGEX.match(date_string)
    if m is None:
        return False
    year, month, day = map(int, m.groups())
    if not year:
        # Year 0 is not valid a valid date
        return False
    (_, max_day) = calendar.monthrange(year, month)
    if not 1 <= day <= max_day:
        return False
    return True