What is the keyword to get time in milliseconds in robot framework? - testing

Currently I am getting time with the keyword Get time epoch , which is returning time in seconds. But I need time in milliseconds , So that I can get time span for a particular event.
or is there any other way to get the time span for a particular event or a testsceanrio?

Check the new test library DateTime, which contains keyword Get Current Date, which also returns milliseconds. It also has keyword Subtract Dates to calculate difference between two timestamps.

One of the more powerful features of robot is that you can directly call python code from a test script using the Evaluate keyword. For example, you can call the time.time() function, and do a little math:
*** Test cases
| Example getting the time in milliseconds
| | ${ms}= | Evaluate | int(round(time.time() * 1000)) | time
| | log | time in ms: ${ms}
Note that even though time.time returns a floating point value, not all systems will return a value more precise than one second.

Using the DateTime library, as suggested by janne:
*** Settings ***
Library DateTime
*** Test Cases ***
Performance Test
${timeAvgMs} = Test wall clock time 100 MyKeywordToPerformanceTest and optional arguments
Should be true ${timeAvgMs} < 50
*** Keywords ***
MyKeywordToPerformanceTest
# Do something here
Test wall clock time
[Arguments] ${iterations} #{commandAndArgs}
${timeBefore} = Get Current Date
:FOR ${it} IN RANGE ${iterations}
\ #{commandAndArgs}
${timeAfter} = Get Current Date
${timeTotalMs} = Subtract Date From Date ${timeAfter} ${timeBefore} result_format=number
${timeAvgMs} = Evaluate int(${timeTotalMs} / ${iterations} * 1000)
Return from keyword ${timeAvgMs}

In the report, for each suite, test and keyword, you have the information about start, end and length with millisecond details. Something like:
Start / End / Elapsed: 20140602 10:57:15.948 / 20140602 10:57:16.985 / 00:00:01.037

I don't see a way to do it using Builtin, look:
def get_time(format='timestamp', time_=None):
"""Return the given or current time in requested format.
If time is not given, current time is used. How time is returned is
is deternined based on the given 'format' string as follows. Note that all
checks are case insensitive.
- If 'format' contains word 'epoch' the time is returned in seconds after
the unix epoch.
- If 'format' contains any of the words 'year', 'month', 'day', 'hour',
'min' or 'sec' only selected parts are returned. The order of the returned
parts is always the one in previous sentence and order of words in
'format' is not significant. Parts are returned as zero padded strings
(e.g. May -> '05').
- Otherwise (and by default) the time is returned as a timestamp string in
format '2006-02-24 15:08:31'
"""
time_ = int(time_ or time.time())
format = format.lower()
# 1) Return time in seconds since epoc
if 'epoch' in format:
return time_
timetuple = time.localtime(time_)
parts = []
for i, match in enumerate('year month day hour min sec'.split()):
if match in format:
parts.append('%.2d' % timetuple[i])
# 2) Return time as timestamp
if not parts:
return format_time(timetuple, daysep='-')
# Return requested parts of the time
elif len(parts) == 1:
return parts[0]
else:
return parts
You have to write your own module, you need something like:
import time
def get_time_in_millies():
time_millies = lambda: int(round(time.time() * 1000))
return time_millies
Then import this library in Ride for the suite and you can use the method name like keyword, in my case it would be Get Time In Millies. More info here.

Related

TypeError: '<' not supported between instances of 'int' and 'Timestamp'

I am trying to change the product name when the period between the expiry date and today is less than 6 months. When I try to add the color, the following error appears:
TypeError: '<' not supported between instances of 'int' and 'Timestamp'.
Validade is the column where the products expiry dates are in. How do I solve it?
epi1 = pd.read_excel('/content/timadatepandasepi.xlsx')
epi2 = epi1.dropna(subset=['Validade'])`
pd.DatetimeIndex(epi2['Validade'])
today = pd.to_datetime('today').normalize()
epi2['ate_vencer'] = (epi2['Validade'] - today) /np.timedelta64(1, 'M')
def add_color(x):
if 0 <x< epi2['ate_vencer']:
color='red'
return f'background = {color}'
epi2.style.applymap(add_color, subset=['Validade'])
Looking at your data, it seems that you're subtracting two dates and using this result inside your comparison. The problem is likely occurring because df['date1'] - today returns a pandas.Series with values of type pandas._libs.tslibs.timedeltas.Timedelta, and this type of object does not allow you to make comparisons with integers. Here's a possible solution:
epi2['ate_vencer'] = (epi2['Validade'] - today).dt.days
# Now you can compare values from `"ate_vencer"` with integers. For example:
def f(x): # Dummy function for demonstration purposes
return 0 < x < 10
epi2['ate_vencer'].apply(f) # This works
Example 1
Here's a similar error to yours, when subtracting dates and calling function f without .dt.days:
Example 2
Here's the same code but instead using .dt.days:

pd.to_timedelta('1D') works while pd.to_timedelta('D') fails. Issue when converting ferquency to timedelta

I'm encountering a silly problem I guess.
Currently, I'm using pd.infer_freq to get the frequency of a dataframe index. Afterwards, I use pd.to_timedelta() to convert this frequency to a timedelta object, to be added to another date.
This works quite fine, except when the dataframe index has a frequency which can be expressed as a single time unit (eg. 1 day, or 1 minute).
To be more precise,
freq = pd.infer_freq(df)
# let's say it gives '2D' because data index is spaced on that interval
timedelta = pd.to_timedelta(freq)
works, while
freq = pd.infer_freq(df)
# let's say it gives 'D' because data index is spaced on that interval
timedelta = pd.to_timedelta(freq)
fails and returns
ValueError: unit abbreviation w/o a number
This could work if I supplied '1D' instead of 'D' though.
I could try to check if the first character of the freq string is numeric, and add '1' otherwise, but that seems quite cumbersome.
Is anyone aware of a better approach ?

Numpy, Pandas Exercise

"[it just needs to be done using numpy and pandas.]"
Your task:
You are asked to write a function that applies ”slack time remaining” (STR) sequencing rule to a given collection of jobs. Although this rule has not been covered in class, application is very similar to critical ratio. You need to calculate STR value for all jobs and schedule the one with the lowest STR. Continue this until all jobs are scheduled. The STR values are calculated as follows:
STR = [Time Until Due Date] − [Processing Time]
If you have more than 1 job with the lowest STR, break ties with Earliest Due Date
(EDD) rule. If due dates are also the same, schedule the one arrived earlier (that means the one in the upper rows of the table.)
Your function will accept a single parameter as pandas dataframe:
Function Parameter:
df jobs: A pandas dataframe whose indexes are the names of the jobs. Jobs
are assumed to be arrived in the same day in the same order given in the dataframe. There
will be two data columns in the dataframe:
ˆ ”Processing Time”: Processing time required for the job
ˆ ”Due Date”: Time between arrival of the job and the due date of the job.
Output: Your function should return a list containing the correct sequence according to STR rule.
Example inputs and expected outputs:
Example Input Data:
Job Processing Time Due Date
A 2 7
B 8 16
C 4 4
D 10 17
E 5 15
F 12 18
Expected Output: [’C’, ’A’, ’F’, ’D’, ’B’, ’E’]
Assuming your input is a DataFrame - your function would be:
def str_list(df):
df = df.set_index('Job')
return (df['Due Date'] - df['Processing Time']).sort_values().index.tolist()

Comparing timedelta fields

I am looking at file delivery times and can't work out how to compare two timedelta fields using a for loop if statement.
time_diff is the difference between cob_date and last_update_time
average_diff is based on the average for a particular file
I want to find the delay for each row.
I have been able to produce a column delay using average_diff - time_diff
However, when the average_diff - time_diff < 0 I just want to return delay = 0 as this is not a delay.
I have made a for loop but this isn't working and I don't know why. I'm sure the answer is very simple but I can't get there.
test_pv_import_v2['delay2'] = pd.to_timedelta('0')
for index, row in test_pv_import_v2.iterrows():
if test_pv_import_v2['time_diff'] > test_pv_import_v2['average_diff'] :
test_pv_import_v2['delay2'] = test_pv_import_v2['time_diff'] - test_pv_import_v2['average_diff']
Use Series.where for set 0 Timedelta by condition:
mask = test_pv_import_v2['time_diff'] > test_pv_import_v2['average_diff']
s = (test_pv_import_v2['time_diff'] - test_pv_import_v2['average_diff'])
test_pv_import_v2['delay2'] = s.where(mask, pd.to_timedelta('0'))

Doing math with sprintf

When creating a label for GNUplot, reading from text files, how would I get the difference in hours:minutes from two columns which each contain an H:M timestamp (e.g. 23.42).
For example, this creates a concatenation of two columns for an existing label:
myDate(col1,col3)=sprintf("%s-%s",strcol(1),strcol(3))
Is it possible modify it to do that date math to get something like:
timeDiffLabel(col5,col6)=sprintf(do-some-math-here,strcol(5),strcol(6))
To parse a time, use the strptime function:
print strptime('%H:%M', '12:34')
This prints 45240.0, which is the number of seconds parsed from the time string.
If you parse the strings from the two columns like this, you can subtract the values and reformat the result with strftime:
timeDiff(c1, c2) = strftime('%k:%M', strptime('%H:%M', strcol(c2)) - strptime('%H:%M', strcol(c1)))
plot 'test.dat' using 0:0:(timeDiff(1,2)) with labels
This works in principle, but only for positive differences. If the difference is e.g. -1, you'll get 23, because the str*time functions work on datetimes.
A more sophisticated solution uses only the absolute value of the difference for the actual formatting, and prepends an optional - to the result:
timeDiff(c1, c2) = (diff = strptime('%H:%M', strcol(c2)) - strptime('%H:%M', strcol(c1)), (diff < 0 ? '-' : '').strftime('%k:%M', abs(diff)))
plot 'test.dat' using 0:0:(timeDiff(1,2)) with labels
So, with a test file like
12:34 23:54
13:45 11:44
2:33 1:11
you get