Python - Working With Time Values

Applies to TestComplete 15.63, last modified on April 23, 2024

In this topic you will learn how to work with time values in Python. The topic includes the following sections:

Basics

Operations over time values are very similar to operations over dates. Each time value includes a date part and vice versa.

Since the TestComplete scripting engine only supports OLE-compatible data types, the date-time values are implemented as floating-point variant values in a special format. The integer part of this value represents the number of days that have passed since December 30, 1899. The number after the decimal separator is time partition: it represents the fraction of a 24-hour period that has elapsed. However, you do not have to understand what these floating-point values represent. TestComplete provides several routines that help you convert these values to their string representation (see below).

Below are some examples of date-time values and their meaning:

Value Meaning
0.25 December 30, 1899. 6:00 AM
36345.5 July 4, 1999. 12:00 PM
39094.65625 January 12, 2007. 3:45 PM

When you are only working with time values the integer part can be omitted. However the time value can vary more than 24 hours and may result in a date-time value that has an integer part.

Objects and Functions for Working With Time Values

TestComplete has an aqDateTime object that contains methods that can be useful when operating with date-time values.

Method Description
AddHours Adds or subtracts the specified number of hours to (from) the given date.
AddMinutes Adds or subtracts the specified number of minutes to (from) the given date.
AddSeconds Adds or subtracts the specified number of seconds to (from) the given date.
AddTime Adds or subtracts the specified number of days, hours, minutes and seconds to (from) the given date.
Compare Compares two specified date/time values.
GetHours Returns the hours part of the specified time value.
GetMinutes Returns the minutes part of the specified time value.
GetSeconds Returns the seconds part of the specified time value.
Now Returns the current date and time.
SetDateTimeElements Returns the Date variable having the specified date and time portions.
SetSystemDateTime Assigns the specified date and time as the system date and time.
SetTimeElements Returns the Date variable having the specified hour, minute and second.
Time Returns the current time.
TimeInterval Calculates the absolute difference between two date/time values.

Another object, aqConvert, provides methods to convert between date values and their string equivalents:

Method Description
DateTimeToFormatStr Converts the given date value to a string using the specified format.
DateTimeToStr Converts the given date value to a string.
StrToDateTime Converts the specified string to a date/time value.
StrToTime Converts the specified string to a time value.

The aqDateTime and aqConvert objects are available for all supported scripting languages, so that you can use them to operate with date values regardless of the chosen language.

Getting Current Time

There are two routines that return the current time: Time and Now. The difference between them is that the value returned by the Now routine includes both date and time parts, whereas the Time routine returns only the time part. The script below demonstrates how to use them.

Python

def GetTime():

  # Obtain the current time 
  TimeValue=aqDateTime.Time()

  # Obtain the current date and time 
  NowValue=aqDateTime.Now()
  
  # Convert the returned date/time values to string values 
  StringTimeValue = aqConvert.DateTimeToStr(TimeValue)
  StringNowValue = aqConvert.DateTimeToStr(NowValue)

  # Post the converted values to the log 
  Log.Message("The time obtained from the Time routine is " + StringTimeValue)
  Log.Message("The time obtained from the Now routine is " + StringNowValue)
  
  # Convert the floating-point values to string values 
  VariantTimeValue = aqConvert.FloatToStr(TimeValue)
  VariantNowValue = aqConvert.FloatToStr(NowValue)

  # Post the converted values to the log 
  Log.Message("The variant representation of TimeValue is "+ VariantTimeValue)
  Log.Message("The variant representation of NowValue is "+ VariantNowValue)

Formatted Output of Time Values

The same date/time value can be represented in various formats. The aqConvert object has two methods that convert a date/time value to a string using the conventional or user-defined format. These methods are DateTimeToStr and DateTimeToFormatStr.

The DateTimeToStr method returns a string that represents the date and time according to the specified location. If a date/time value has only the time portion, then the routine does not display the date.

The DateTimeToFormatStr method allows greater flexibility, since it accepts the format specifier string as one of the parameters. It is capable of forming a string of date and time portions together or in parts. To learn how the resulting format is defined, see Date and Time Format Specifiers.

The example below demonstrates how to use these methods:

Python

def OutputDemo():
  
  # Obtain the current date and time 
  aDateTime=aqDateTime.Now()

  # Convert the returned date/time value to a string and post this string to the log 
  Str = aqConvert.DateTimeToStr(aDateTime)
  Log.Message(Str)

  # Convert the returned date/time value to a string using the specified format and post this string to the log 
  FormatStr = aqConvert.DateTimeToFormatStr(aDateTime, "%A. %B, %d, %Y. %H:%M:%S")
  Log.Message(FormatStr)

Encoding and Decoding Time Values

Since date/time values are implemented as variants, special routines are required to get the hours or minutes portion of those values. You can use the SetTimeElements, GetHours, GetMinutes and GetSeconds methods of the aqDateTime object for this purpose. The SetTimeElements method accepts the time part and returns a variant date/time value.

Python

def EncodeTimeDemo():
  
  # Create a Date variable having the specified hour, minute and second values
  myTime=aqDateTime.SetTimeElements(13,12,25)

  # Convert the value of the myTime variable to a string using the specified format and post this string to the log 
  EncodedTime = aqConvert.DateTimeToFormatStr(myTime, "%H:%M:%S")
  Log.Message("The encoded time is "+ EncodedTime)

  # Convert the value of the myTime variable to a variant value and post it to the log 
  VariantTime = aqConvert.FloatToStr(myTime)
  Log.Message("The variant representation of it is "+ VariantTime)

The GetHours, GetMinutes and GetSeconds methods perform the contrary operation: they accept a variant date/time value and return the respective time parts of that value. Here is an example of how to use these methods:

Python

def DecodeTimeDemo():
  
  # Obtain the current time 
  CurrentTime = aqDateTime.Time()

  # Return the hours, minutes and seconds parts of the current time value and then post them to the log 
  Hours = aqDateTime.GetHours(CurrentTime)
  Minutes = aqDateTime.GetMinutes(CurrentTime)
  Seconds = aqDateTime.GetSeconds(CurrentTime)

  Log.Message(str(Minutes)+ " minute(s) and "+str(Seconds)+" second(s) have passed since the hour "+str(Hours)+" has started.")

Modifying Time Values

The aqDateTime scripting object has a number of methods that alter the time portions of the given date/time value. These methods are: AddHours, AddMinutes, AddSeconds and AddTime. Despite their names, these methods can both increase and decrease the corresponding time portions. If the value of the respective argument (Days, Hours, Minutes or Seconds) is a positive number, the methods add the specified number of days, hours, minutes or seconds to the input date/time. If the argument’s value is negative, then the input date/time is decreased by the given number. The AddTime method allows you to change several time portions simultaneously.

The methods were designed for date/time values, and guarantee a valid resulting value. Thus, for example, changing the minutes portion automatically increases the hours portion if the resulting number of minutes exceeds 59 minutes.

The code snippet below demonstrates how to use these methods:

Python

def ModifyingTimeValues():
  
    CurrentTime=aqDateTime.Time()

    # Increase time by 30 seconds 
    AlteredTime=aqDateTime.AddSeconds(CurrentTime,30)
    Log.Message("Current time: "+aqConvert.DateTimeToStr(CurrentTime))
    Log.Message("Altered time: "+aqConvert.DateTimeToStr(AlteredTime))

    # Decrease time by 2 hours 
    AlteredTime=aqDateTime.AddHours(CurrentTime,-2)
    Log.Message("Current time: "+aqConvert.DateTimeToStr(CurrentTime))
    Log.Message("Altered time: "+aqConvert.DateTimeToStr(AlteredTime))

    # Passing both positive and negative arguments 
    # Increase time by 5 minutes (1 hour minus 55 minutes) 
    AlteredTime=aqDateTime.AddTime(CurrentTime,0,1,-55,0)
    Log.Message("Current time: "+aqConvert.DateTimeToStr(CurrentTime))
    Log.Message("Altered time: "+aqConvert.DateTimeToStr(AlteredTime))

    # Adding 10 minutes to a date value like 11:55 PM, December 31, 1999 changes the whole date 
    Time=aqDateTime.SetDateTimeElements(1999,12,31,23,55,00)
    AlteredTime=aqDateTime.AddMinutes(Time,10)
    Log.Message("Time: "+aqConvert.DateTimeToStr(Time))
    Log.Message("Altered time: "+aqConvert.DateTimeToStr(AlteredTime))

Comparing Time Values

To compare date/time values, use the aqDateTime.Compare method rather than comparison operators (like ==, >, <, != and others) provided by the scripting engine:

Python

def Compare():
  r = aqDateTime.Compare(DateTime1, DateTime2);
  if r > 0:
    # DateTime1 > DateTime2 
    ...
  elif r < 0:
    # DateTime1 < DateTime2 
    ...
  else: 
    # DateTime1 == DateTime2 
    ...

This note does not concern the Date objects provided by the Python engine. This object is used to store date and time values. To compare Date objects, use the features provided by the engine.

Using the StopWatch Object

Sometimes, you may need to measure the time that has passed between two events, for example, between the beginning and the end of a test run. This can be done in two ways: using the time-handling routines of the aqDateTime object and using the StopWatch object provided by the HISUtils plugin.

In the first case, you should obtain the current time before and after the event, and calculate the interval between them (for example, with the aqDateTime.TimeInterval method).

In the second case, you should create an instance of the StopWatch object, start the time count using the StopWatch.Start method, execute the desired operation and then stop the counter using the StopWatch.Stop method.

Below is a sample code that demonstrates how to use both techniques:

Python

# Using the time-handling routines of the aqDateTime object 
def MeasureTestTime1():
  
  # Obtain the current date and time before calling the test 
  TimeBefore=aqDateTime.Now()

  # Call the test whose execution time you need to measure 
  DoTest1()

  # Obtain the current date and time after calling the test 
  TimeAfter=aqDateTime.Now()
  Log.Message("Test1 finished.")

  # Calculate the execution time and post it to the log 
  Log.Message (aqDateTime.TimeInterval(TimeBefore, TimeAfter))

# Using the StopWatch object 
def MeasureTestTime2():
  # Access the StopWatch object 
  StopWatchObj = HISUtils.StopWatch

  # Start the time counter 
  StopWatchObj.Start()

  # Call the test whose execution time you need to measure 
  DoTest1()

  # Stop the time counter 
  StopWatchObj.Stop()
  Log.Message("Test1 finished.")

  # Calculate the execution time and post it to the log 
  Log.Message("Execution time: " + StopWatchObj.ToString())

def DoTest1():
  # Your code here 
  ...

As you can see, both methods are equivalent, yet, the StopWatch object has a special method, ToString, that transforms the time counter value to a string. Furthermore, the object has the Split method that allows you to get the time counter value without stopping the counter. This can be useful when displaying the elapsed time during a series of tests:

Python

def MeasureTestTime3():
  StopWatchObj = HISUtils.StopWatch;

  # Start the time counter 
  StopWatchObj.Start();
  for i in range(1, 5):
    DoTest1()

    # Return the time that has passed since the start of the time counter 
    StopWatchObj.Split()

    # Calculate the elapsed time and post it to the log 
    Log.Message("Iteration: "+str(i)+". Time elapsed: "+StopWatchObj.ToString())
  StopWatchObj.Stop()
  Log.Message("Test1 finished.")

  # Calculate the total execution time 
  Log.Message("Execution time: " + StopWatchObj.ToString())

See Also

Working With Time
Python - Working With Date Values
aqDateTime Object

Highlight search results