Date calculations

Hi.

I´m calculating a date using next code:

from datetime import datetime, date, time, timedelta
import calendar
event.source.text=datetime.today()-timedelta(days=4)

I would like to show the result in an Ignition´s object or save it in a tag, however there is an error because I must to convert it from date to string. How can I save that value?

Traceback (most recent call last):
File “event:mouseClicked”, line 3, in
TypeError: can’t convert datetime.datetime(2020, 6, 12, 10, 36, 26, 306999) to java.lang.String

Ignition v7.9.10 (b2018112821)
Java: Oracle Corporation 1.8.0_201

The best way to do dates in Ignition is though the system.date functions. The second best way is to use the native java Calendar and date classes (the system functions use these under the hood). I would try not to use the python datetime library.

All Ignition components use java date objects, so you’ll be able to use dates generated by the native functions much more easily.

2 Likes

Some example code for what zacht suggested:

now = system.date.now()
fourDaysAgo = system.date.addDays(now, -4)
dateString = system.date.format(fourDaysAgo, "yyyy-MM-dd HH:mm:ss")
# note - if you make the tag a Date type you can store fourDaysAgo directly
1 Like