Substract two time fields in index pattern

Hello dears

I have an instance of heartbeat that check all of certificates of my websites. every log looks like this:

  "_index": "heartbeat-7.16.2-2022.08.01-000001",
  "_type": "_doc",
  "_score": 1,
  "_source": {
    "@timestamp": "2022-08-06T10:47:49.130Z",
    "ip": "My IP",
    "url": {
      "scheme": "https",
      "domain": "",
      "port": 443,
    "tls": {
      "certificate_not_valid_after": "2022-10-19T09:39:32.000Z",
      "established": true,

I want to create a field in heartbeat-* index pattern in Scripted fields to create a new field with name remaining_time which is day reminder of certificate validation.

All I want is a script that substract @timestamp with certificate_not_valid_after field so I can have remaining time for my certificates.

My problem is, how should I write this script in Scripted fields in order to create a new field?

I'm using Elasticstack version 7.16.2

Thank you all

You would be better off using Runtime fields | Elasticsearch Guide [7.16] | Elastic instead of scripted fields.

Something like this should work;

if (!doc['field1'].empty && !doc['field2'].empty) {
  return ((doc['field1'].value - doc['field2'].value.millis) / 1000);
} else {
  return 0;

Thank you so much

I have got the require information from "Uptime" observability