-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
84 lines (72 loc) · 2.88 KB
/
utils.py
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# -*- coding: utf-8 -*-
"""
Contains some extra filters for Jinja2.
To use these, they need to be registered in your pyramid config.
"""
from dateutil import parser
def set_attr_filter(target, key, value):
"""
Jinja2 filter that sets an attribute of an object.
"""
target[key] = value
return target
def datetime_format_filter(value, format='%d-%m-%Y %H:%M'):
"""
Jinja 2 filter to print a datetime object in a template.
:param value: Eiter a :class:`datetime.datetime` or a string that can be \
parsed by :class:`dateutil.parser`. In case of ambiguity between the \
day and the month, the parser will assume the day precedes the month \
(ie. European way)
:param format: The format to print the date in.
:return: The formatted date, eg. `07-09-2014 20:00`.
"""
if value:
try:
return value.strftime(format)
except AttributeError:
if value[0:4].find('-') == -1 and value[0:4].find('/') == -1:
date = parser.parse(value, yearfirst=True, dayfirst=False)
else:
date = parser.parse(value, dayfirst=True)
return date.strftime(format)
else:
return ''
def fuzzy_date_format_filter(value, format='%d-%m-%Y'):
"""
Jinja 2 filter to print a fuzzy date object in a template.
:param value: Eiter a :class:`datetime.datetime` or a string that can be \
parsed by :class:`dateutil.parser`. In case of ambiguity between the \
day and the month, the parser will assume the day precedes the month \
(ie. European way)
:param format: The format to print the date in.
:return: The formatted date, eg. `07-09-2014 20:00`.
"""
if value:
try:
return _fuzzy_date_formatter(value, format)
except AttributeError:
if value[0:4].find('-') == -1 and value[0:4].find('/') == -1:
date = parser.parse(value, yearfirst=True, dayfirst=False)
else:
date = parser.parse(value, dayfirst=True)
return _fuzzy_date_formatter(date, format)
else:
return ''
def _fuzzy_date_formatter(date, format='%d-%m-%Y'):
"""
Dateconverter to convert date or datetime objects to strings in a specific format
Implemented because of the problems of datetime.strftime method with years before 1900
:param date:
:param format: The format to print the date in. (must be a predefined format)
'%d-%m-%Y' or '%m-%Y' or '%Y'
:return: The formatted date, eg. `07-09-2014`
"""
if format == '%d-%m-%Y':
return '{0.day:02d}-{0.month:02d}-{0.year:4d}'.format(date)
elif format == '%m-%Y':
return '{0.month:02d}-{0.year:4d}'.format(date)
elif format == '%Y':
return '{0.year:4d}'.format(date)
else:
# Default
return '{0.day:02d}-{0.month:02d}-{0.year:4d}'.format(date)