Subtract n days

This code works in the script console of the ignition designer. But, it produces an error when in a WebDev script.

I’m just trying to subtract ‘n’ days from today’s date i.e.

import datetime
timeNow = datetime.datetime.now()
timeBefore = timeNow - datetime.timedelta(days=1)

I would get

in doGet NameError: global name ‘timedelta’ is not defined

Any help is appreciated.

Try

system.date.addDays(system.date.now(),-1)

2 Likes

Another solid alternative is to use java.util.Calendar
It’s got Calendar.add(Field, amount) as a function and handles that nicely.

Also it might not be clear from your example, do you use timedelta somewhere else in the code of that method?
Usually an error like globalname not defined is caused by use of a variable that isn’t scoped. Could be another method or line entirely.

+1 to using java.util.calendar. Plus the java.util.date is becoming more and more depreciated, as a rule it really shouldn’t be used.

# Calendar Class has built in addition/subtraction of dates, also the Date class is largely depreceated.
from java.util import Calendar
	
# Create a calendar with the current time
rightNow = Calendar.getInstance()

#To add of subtract hours
rightNow.add(rightNow.HOUR, -1)

# To add or subtract weeks
rightNow.add(rightNow.WEEK_OF_YEAR, -1)

# To add or subtract months
rightNow.add(rightNow.MONTH, -1)

# To add or subtract years
rightNow.add(rightNow.YEAR, -1)

#To assign a date/time property in Ignition (such as a trend start date) with the new time
trend = event.source.parent.getComponent('TREND')
trend.startDate = rightNow.time

good point. i’ll check. thank you.