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 tsfromat(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 tdiffsec(date1, date2):
60 """ Returns the date difference ( date1 - date2 ) in seconds,
61 where date1 and date 2 are datetime objects
64 diff = tdiff(date1, date2)
65 return diff.total_seconds()
67 def stabsformat(sdate, dbase = None):
68 """ Constructs a datetime object from a string date.
69 The string date can be expressed as an absolute date
70 ( i.e. format YYYYMMddHHMMSSffff ) or as a relative time
71 ( e.g. format '5m' or '10s').
72 If the date is a relative time and the dbase parameter
73 is given (dbase must be datetime object), the returned
74 date will be dbase + sdate. If dbase is None,
75 current time will be used instead as base time.
77 :param date : string date
82 # No date given, return current datetime
86 # Absolute date is given
87 if _reabs.match(sdate):
88 return stformat(sdate)
90 # Relative time is given
91 m = _rerel.match(sdate)
93 time = float(m.groupdict()['time'])
94 units = m.groupdict()['units']
96 delta = datetime.timedelta(hours = time)
98 delta = datetime.timedelta(minutes = time)
100 delta = datetime.timedelta(seconds = time)
102 delta = datetime.timedelta(microseconds = (time*1000))
104 delta = datetime.timedelta(microseconds = time)