Commit 820e90a55d181deb9e881b41fc1e46e2248fe03b

Authored by mykhaly
1 parent 39118458

Rewrite compare_date in service_keywords.py

In order to have possibility to compare dates with accuracy passed in
human-readable format
@@ -68,16 +68,54 @@ def get_file_contents(path): @@ -68,16 +68,54 @@ def get_file_contents(path):
68 return unicode(f.read()) or u'' 68 return unicode(f.read()) or u''
69 69
70 70
71 -def compare_date(date1, date2, accuracy): 71 +def compare_date(date1, date2, accuracy="minute", absolute_delta=True):
  72 + '''Compares dates with specified accuracy
  73 +
  74 + Before comparison dates are parsed into datetime.datetime format
  75 + and localized.
  76 +
  77 + :param date1: First date
  78 + :param date2: Second date
  79 + :param accuracy: Max difference between dates to consider them equal
  80 + Default value - "minute"
  81 + Possible values - "day", "hour", "minute" or float value
  82 + of seconds
  83 + :param absolute_delta: Type of comparison. If set to True, then no matter which date order. If set to
  84 + False then date2 must be lower then date1 for accuracy value.
  85 + Default value - True
  86 + Possible values - True and False or something what can be casted into them
  87 + :returns: Boolean value
  88 +
  89 + :error: ValueError when there is problem with converting accuracy
  90 + into float value. When it will be catched warning will be
  91 + given and accuracy will be set to 60.
  92 +
  93 + '''
72 date1 = parse(date1) 94 date1 = parse(date1)
73 date2 = parse(date2) 95 date2 = parse(date2)
  96 +
74 if date1.tzinfo is None: 97 if date1.tzinfo is None:
75 date1 = TZ.localize(date1) 98 date1 = TZ.localize(date1)
76 if date2.tzinfo is None: 99 if date2.tzinfo is None:
77 date2 = TZ.localize(date2) 100 date2 = TZ.localize(date2)
78 101
79 delta = (date1 - date2).total_seconds() 102 delta = (date1 - date2).total_seconds()
80 - if abs(delta) > accuracy: 103 +
  104 + if accuracy == "day":
  105 + accuracy = 24 * 60 * 60 - 1
  106 + elif accuracy == "hour":
  107 + accuracy = 60 * 60 - 1
  108 + elif accuracy == "minute":
  109 + accuracy = 60 - 1
  110 + else:
  111 + try:
  112 + accuracy = float(accuracy)
  113 + except ValueError:
  114 + LOGGER.log_message(Message("Could not convert from {} to float. Accuracy is set to 60 seconds.".format(accuracy), "WARN"))
  115 + accuracy = 60
  116 + if absolute_delta:
  117 + delta = abs(delta)
  118 + if delta > accuracy:
81 return False 119 return False
82 return True 120 return True
83 121
Please register or login to post a comment