2 # NEPI, a framework to manage network experiments
3 # Copyright (C) 2013 INRIA
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.
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.
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/>.
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
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)$")
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)
32 """ Constructs a datetime object from a string date with
33 format YYYYMMddHHMMSSffff
36 return datetime.datetime.strptime(sdate, _strf).date()
38 def tsformat(date = None):
39 """ Formats a datetime object to a string with format YYYYMMddHHMMSSffff.
40 If no date is given, the current date is used.
46 return date.strftime(_strf)
49 """ Returns datetime object with the current time """
50 return datetime.datetime.now()
52 def tdiff(date1, date2):
53 """ Returns difference ( date1 - date2 ) as a datetime object,
54 where date1 and date 2 are datetime objects
59 def _get_total_seconds(td):
60 return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 1e6) / 1e6
62 def tdiffsec(date1, date2):
63 """ Returns the date difference ( date1 - date2 ) in seconds,
64 where date1 and date 2 are datetime objects
67 diff = tdiff(date1, date2)
68 return _get_total_seconds(diff)
70 def stabsformat(sdate, dbase = None):
71 """ Constructs a datetime object from a string date.
72 The string date can be expressed as an absolute date
73 ( i.e. format YYYYMMddHHMMSSffff ) or as a relative time
74 ( e.g. format '5m' or '10s').
75 If the date is a relative time and the dbase parameter
76 is given (dbase must be datetime object), the returned
77 date will be dbase + sdate. If dbase is None,
78 current time will be used instead as base time.
80 :param date : string date
85 # No date given, return current datetime
89 # Absolute date is given
90 if _reabs.match(sdate):
91 return stformat(sdate)
93 # Relative time is given
94 m = _rerel.match(sdate)
96 time = float(m.groupdict()['time'])
97 units = m.groupdict()['units']
99 delta = datetime.timedelta(hours = time)
101 delta = datetime.timedelta(minutes = time)
103 delta = datetime.timedelta(seconds = time)
105 delta = datetime.timedelta(microseconds = (time*1000))
107 delta = datetime.timedelta(microseconds = time)