Dates in Jython

We want to subtract two dates in our Jython script and find out how many days have passed. Also, we would like to convert a date to a string that we can pass back to SQL to update the tables.

We are assigining a variable in our script a date from a component. We assume this is a python date type. When we called strftime on the date object we get a type mismatch error.

querydFill = event.source.parent.getComponent(‘calFillDate’).date

fpmi.db.runUpdateQuery(“UPDATE LookUpFermantationTanks SET ProjFillDate = ‘%s’ WHERE FERMTANKID = ‘%s’” % (querydFill.strftime("%Y-%m-%d %H-%M-%S"), keyValue1), ‘LabSNB01’)

The value you’re getting back from the calendar component is a java Date object. Python uses tuples of values to represent a date. (see docs.python.org/lib/module-time.html)

You can make a python date from a java date like this:

from time import * date = event.source.parent.getComponent("Calendar").date pyDate = localtime(date.time/1000)

So your code would look like this:

[code]from time import *
querydFill = event.source.parent.getComponent(‘calFillDate’).date
querydFill = localtime(querydFill.time/1000)

fpmi.db.runUpdateQuery(“UPDATE LookUpFermantationTanks SET ProjFillDate = ‘%s’ WHERE FERMTANKID = ‘%s’” % (strftime("%Y-%m-%d %H-%M-%S", querydFill), keyValue1), ‘LabSNB01’)[/code]

Or, you could have used fpmi.db.dateFormat to skip the whole Python date stuff, like this:

[code]querydFill = event.source.parent.getComponent(‘calFillDate’).date
timeStr = fpmi.db.dateFormat(querydFill, “yyyy-MM-dd HH:mm:ss”)

fpmi.db.runUpdateQuery(“UPDATE LookUpFermantationTanks SET ProjFillDate = ‘%s’ WHERE FERMTANKID = ‘%s’” % (timeStr, keyValue1), ‘LabSNB01’)[/code]

Hope this helps,

Ron,

Here’s a simple version of a method to get the difference between two java dates.

[code]def dateDiff(startDate, endDate, period=“seconds”):
import java.util.Date
if startDate.class != endDate.class != java.util.Date:
return None

period = period.lower()
if period == “days”:
return (endDate.getTime() - startDate.getTime()) / 86400000
elif period == “hours”:
return (endDate.getTime() - startDate.getTime()) / 3600000
elif period == “minutes”:
return (endDate.getTime() - startDate.getTime()) / 60000
elif period == “seconds”:
return (endDate.getTime() - startDate.getTime()) / 1000;
else:
return None[/code]

Note: This method may not properly handle Daylight Savings Time. (see http://www.xmission.com/~goodhill/dates/deltaDates.html)

Also, check out this thread: inductiveautomation.com/foru … php?t=3235