Python timedelta() error

I’m trying to update a session variable sessDateStart with an offset number of days from another variable sessDateEnd using datetime’s timedelta function. When I run this code from a test button I get stuck at the last line (of the snippet) …

	import datetime
	from datetime import timedelta

	system.perspective.print(self.session.custom.sessDateEnd)		# 2020-12-09 12:00:00.000
	system.perspective.print(type(self.session.custom.sessDateEnd))	# class java.util.Date
	d2 = self.session.custom.sessDateEnd
	system.perspective.print(type(d2))								# class java.util.Date
	d = self.session.custom.sessDateDays
	system.perspective.print(d)										# Returns 7.
	system.perspective.print(type(d))								# class org.python.core.PyUnicode
	d1 = d2 + timedelta(days=d)

… with the error message …

[AWT-EventQueue-0] ERROR com.inductiveautomation.ignition.client.util.gui.ErrorUtil - Error running action 'dom.onClick' on subViews/viewMain@D/root/FlexContainer_0/FlexContainer/Button_0: Traceback (most recent call last):
  File "<function:runAction>", line 12, in runAction
  File "C:\Program Files\Inductive Automation\Ignition\user-lib\pylib\datetime.py", line 499, in __new__
    days += weeks*7
TypeError: cannot concatenate 'unicode' and 'int' objects

I’ve searched this forum and the usual StackExchange sites but can’t find my error. Can anyone give me some guidance?

[Ignition 8.1 / Jython 2.7]

It means sessDateEnd is a string (unicode is a flavor of string), not java.util.Date. Probably getting that from a bound date entry component.

FWIW, you should avoid jython’s datetime. There be dragons. Use java’s Date and Calendar and related classes instead.

The system.date scripting functions should make this easier as well.

2 Likes

Thanks, Phil. I’ve seen you recommending this in several posts. I think it’s starting to dawn on me that I just need to use the system.date functions.

	# DateStart = DateEnd - numberOfDays
	self.session.custom.sessDateStart = system.date.addDays(
		self.session.custom.sessDateEnd, 
		- int(self.session.custom.sessDateDays)
	)