Hi Guys,
I am pulling a "last_seen" tag (datetime in a string datatype) from a json object coming from an MQTT server.
In Ignition I have a referance tag that points to the MQTT tag, it has an on value change event script that runs when this value updates.
from datetime import datetime
<There is a bunch of other code here not relevant - will post if required. >
# If date time convert string to datetime object
if key == "last_seen":
print "The time string is " + value[0]
value2 = [datetime.strptime(value[0], '%Y-%m-%dT%H:%M:%S+11:00')]
print "The time conversion is " + str(value2[0])
system.tag.writeBlocking(path,value2)
else:
system.tag.writeBlocking(path,value)
The print output is:
The time string is 2022-10-13T18:59:11+11:00
The time conversion is 2022-10-13 18:59:11
But the datetime tag vaule is "2022-10-14 05:59:11.0" as you can see it is 23 hours ahead.
I have checked the MQTT and the Igntion servers OS and both are set for the same time and time zone.
The correct tag is written to when this runs, the value is just wrong
Convert time from str is always little bite tricky.
If you have java.date in input and you want convert it in datetime, just do that:
from datetime import datetime
dt = datetime.fromtimestamp(yourJavaDate.getTime()/1000.0)
But if you absolutely want to parse the date from the string, it's more complex.
In your script you intentionally omit the timezone (+11:00), which explains your difference.
Don't use jython's datetime module. It is buggy, particularly when using non-US timezones. Use java's classes (and the Ignition system.date.* functions).
The 'T' is not a valid character in system.date.parse(). OffsetDateTime can parse it, though. Then we can convert it to an Instant and then to a Date.
from java.time import OffsetDateTime
from java.util import Date
timeIn = '2022-10-13T18:59:11+11:00'
t = OffsetDateTime.parse(timeIn).toInstant()
timeOut = Date.from(t)
Gotta thank you so much for a little blurb you said in another post that stated that Ignition uses java date objects as this allowed me to skip all the super frustrating datetime.strptime() junk when trying to parse a date from a web_dev call. Once I found that I looked up this post and grabbed the relevant java code and things worked so much easier. Thanks!