18ed0275d55d88d32b56c12dd46f349dabfdc578
[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 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
19
20
21 import datetime
22 import re
23
24 _strf = "%Y%m%d%H%M%S%f"
25 _reabs = re.compile("^\d{20}$")
26 _rerel = re.compile("^(?P<time>\d+(.\d+)?)(?P<units>h|m|s|ms|us)$")
27
28 # Work around to fix "ImportError: Failed to import _strptime because the import lock is held by another thread."
29 datetime.datetime.strptime("20120807124732894211", _strf)
30
31 def strfnow():
32     """ Current date """
33     return datetime.datetime.now().strftime(_strf)
34
35 def strfdiff(str1, str2):
36     # Time difference in seconds without ignoring miliseconds
37     d1 = datetime.datetime.strptime(str1, _strf)
38     d2 = datetime.datetime.strptime(str2, _strf)
39     diff = d1 - d2
40     ddays = diff.days * 86400
41     dus = round(diff.microseconds * 1.0e-06, 2) 
42     ret = ddays + diff.seconds + dus
43     # delay must be > 0
44     return (ret or 0.001)
45
46 def strfvalid(date):
47     """ User defined date to scheduler date 
48     
49     :param date : user define date matchin the pattern _strf 
50     :type date : date 
51
52     """
53     if not date:
54         return strfnow()
55     if _reabs.match(date):
56         return date
57     m = _rerel.match(date)
58     if m:
59         time = float(m.groupdict()['time'])
60         units = m.groupdict()['units']
61         if units == 'h':
62             delta = datetime.timedelta(hours = time) 
63         elif units == 'm':
64             delta = datetime.timedelta(minutes = time) 
65         elif units == 's':
66             delta = datetime.timedelta(seconds = time) 
67         elif units == 'ms':
68             delta = datetime.timedelta(microseconds = (time*1000)) 
69         else:
70             delta = datetime.timedelta(microseconds = time) 
71         now = datetime.datetime.now()
72         d = now + delta
73         return d.strftime(_strf)
74     return None
75