Debian Codegraph @

src/timeago/__init__.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 '''
4 Created on 2016-5-26
5
6 @author: hustcc
7 '''
8
9 from datetime import datetime, timedelta
10 from timeago.locales import timeago_template
11 from timeago.excepts import ParameterUnvalid
12 from timeago import parser
13 from timeago.setting import DEFAULT_LOCALE
14
15 __version__ = '1.0.14'
16 __license__ = 'MIT'
17 __ALL__ = ['format']
18
19
20 # Original fix #2 for Py2.6
21 def total_seconds(dt):
22 # Keep backward compatibility with Python 2.6 which doesn't have
23 # this method
24 if hasattr(datetime, 'total_seconds'):
25 return dt.total_seconds()
26 else:
27 return (dt.microseconds +
28 (dt.seconds + dt.days * 24 * 3600) * 10**6) / 10**6
29
30
31 # second, minute, hour, day, week, month, year(365 days)
32 SEC_ARRAY = [60.0, 60.0, 24.0, 7.0, 365.0 / 7.0 / 12.0, 12.0]
33 SEC_ARRAY_LEN = 6
34
35
36 def format(date, now=None, locale='en'):
37 '''
38 the entry method
39 '''
40 if not isinstance(date, timedelta):
41 if now is None:
42 now = datetime.now()
43 date = parser.parse(date)
44 now = parser.parse(now)
45
46 if date is None:
47 raise ParameterUnvalid('the parameter `date` should be datetime '
48 '/ timedelta, or datetime formatted string.')
49 if now is None:
50 raise ParameterUnvalid('the parameter `now` should be datetime, '
51 'or datetime formatted string.')
52 date = now - date
53 # the gap sec
54 diff_seconds = int(total_seconds(date))
55
56 # is ago or in
57 ago_in = 0
58 if diff_seconds < 0:
59 ago_in = 1 # date is later then now, is the time in future
60 diff_seconds *= -1 # change to positive
61
62 tmp = 0
63 i = 0
64 while i < SEC_ARRAY_LEN:
65 tmp = SEC_ARRAY[i]
66 if diff_seconds >= tmp:
67 i += 1
68 diff_seconds /= tmp
69 else:
70 break
71 diff_seconds = int(diff_seconds)
72 i *= 2
73
74 if diff_seconds > (i == 0 and 9 or 1):
75 i += 1
76
77 if locale is None:
78 locale = DEFAULT_LOCALE
79
80 tmp = timeago_template(locale, i, ago_in)
81 if hasattr(tmp, '__call__'):
82 tmp = tmp(diff_seconds)
83 return '%s' in tmp and tmp % diff_seconds or tmp