java.sql.Timestamp and datetime.datime

Hi all,

I created a memory tag in Ignition which record the datetime of a particular event.

In a component I read the value of the datetime in the memory tag and I compare it with datetime.datatime.now() simple by:

lastDatetime = system.tag.read(lastDatetimeTagPath).value td = datetime.datetime.now() - lastDatetime

to check how long the time has lasted since the event and Ignition gives run time error.

After my further check, I realized that the run time error is caused by the script line:

td = datetime.datetime.now() - lastDatetime

because the type of datetime.datetime.now() is ā€œdatetime.datimeā€ while lastDatetime is ā€œjava.sql.Timestampā€

My question is how can we get time difference between datetime.datetime and java.sql.Timestamp object in Ignition?

Or else, is there a way to convert java.sql.Timestamp object to datetime.datetime object?

Thank you!

Hi all,

I managed to convert java.sql.Timestamp to datetime.datetime by:

dtObj = datetime.datetime(tsObj.year + 1900, tsObj.month + 1, tsObj.date, tsObj.getHours(), tsObj.getMinutes(), tsObj.getSeconds())

I am not sure if this is the best way to do it, since I lost the millisecond precision here.

Is there any conversion way which retain the millisecond precision?

Rather than using datetime, the Scripting / Python / Python in Ignition / Working with Different Datatypes section of the manual points out it is easier to use the Java java.util.Date class.

The following script should let you do what you want:

# Use the java Date class, the same as a memory tag of type DateTime.
from java.util import Date

# This returns the current time.
now = Date()
# Read the value of the memory tag.
lastDatetime = system.tag.read('New Tag').value
# The getTime() function returns the DateTime in milliseconds, so you 
# can subtract one from the other. The result is in milliseconds.
tdMillis = now.getTime() - lastDatetime.getTime()
# If you wish you can create another Date object from the millisecond value.
td = Date(tdMillis)
# The dateFormat command allows you to format the Date object any way you want.
print tdMillis, system.db.dateFormat(td, "mm:ss.S")
2 Likes

Hi AlThePal,

Thanks for the reply. Yes, I found working with Date() is easier. :slight_smile: