Added LICENSE
[nepi.git] / src / nepi / util / timefuncs.py
1 """
2     NEPI, a framework to manage network experiments
3     Copyright (C) 2013 INRIA
4
5     This program is free software: you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation, either version 3 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 """
19
20 import datetime
21 import re
22
23 _strf = "%Y%m%d%H%M%S%f"
24 _reabs = re.compile("^\d{20}$")
25 _rerel = re.compile("^(?P<time>\d+(.\d+)?)(?P<units>h|m|s|ms|us)$")
26
27 # Work around to fix "ImportError: Failed to import _strptime because the import lock is held by another thread."
28 datetime.datetime.strptime("20120807124732894211", _strf)
29
30 def strfnow():
31     """ Current date """
32     return datetime.datetime.now().strftime(_strf)
33
34 def strfdiff(str1, str2):
35     # Time difference in seconds without ignoring miliseconds
36     d1 = datetime.datetime.strptime(str1, _strf)
37     d2 = datetime.datetime.strptime(str2, _strf)
38     diff = d1 - d2
39     ddays = diff.days * 86400
40     dus = round(diff.microseconds * 1.0e-06, 2) 
41     ret = ddays + diff.seconds + dus
42     # delay must be > 0
43     return (ret or 0.001)
44
45 def strfvalid(date):
46     """ User defined date to scheduler date 
47     
48     :param date : user define date matchin the pattern _strf 
49     :type date : date 
50
51     """
52     if not date:
53         return strfnow()
54     if _reabs.match(date):
55         return date
56     m = _rerel.match(date)
57     if m:
58         time = float(m.groupdict()['time'])
59         units = m.groupdict()['units']
60         if units == 'h':
61             delta = datetime.timedelta(hours = time) 
62         elif units == 'm':
63             delta = datetime.timedelta(minutes = time) 
64         elif units == 's':
65             delta = datetime.timedelta(seconds = time) 
66         elif units == 'ms':
67             delta = datetime.timedelta(microseconds = (time*1000)) 
68         else:
69             delta = datetime.timedelta(microseconds = time) 
70         now = datetime.datetime.now()
71         d = now + delta
72         return d.strftime(_strf)
73     return None
74