comparing strings - Lua - string

I have a file (termino.txt) that is all filled in the following format :
pay the bill
2015-08-30T13:22:53.108Z
Go to the doctor
2015-09-30T13:22:53.108Z
....
All the even lines are of the form RFC 3339 timestamp. What I need is to compare today's date with these dates the file to see if they are the same. I'm trying this:
local function verifica(evt)
local nome= ''
local dia = ''
local turn = 1
local data = os.date("%x")
local file = io.open("termino.txt", "r")
while true do
nome = dia
line = file:read()
dia = line
if (turn %2 == 0) then
> Here I need to compare "data" with "dia" that will receive string with RFC 3339 timestamp format.
end
turn ++
end
end
I need help to make this comparison! Thanks

local dia = '2015-10-6T13:22:53.108Z'
-- parse date info from the RFC 3339 timestamp
local year, month, day = dia:match('(%d+)-(%d+)-(%d+)')
-- get today's date from Lua, in table format
local today = os.date('*t')
-- compare
if tonumber(year) == today.year
and tonumber(month) == today.month
and tonumber(day) == today.day then
-- the dates match
end

Related

Custom date format in KQL

I would like to know if there is a possibility to customize the format of a specific datetime in KQL.
For example I have the following code:
let value = format_datetime(datetime(07:30:00), "HH:mm");
print value
As a result we obtain 07:30
My question here is that instead of having 07:30, is there a possibility to format it in a way to have a value = 7hr 30m
based on if your input is a datetime or a timespan value, you can try either of the following options (using some string manipulation):
print ts = timespan(07:30:00)
| project output = strcat(toint(ts/1h), "hr ", toint(ts/1m)%60, "min")
print dt = datetime(2021-02-16 07:30:00)
| project output = strcat(datetime_part("hour", dt), "hr ", datetime_part("minute", dt), "min")

Lua How to reformat a date?

I am currently retrieving a date in the format of 2020-09-23T09:03:46.242Z (YYYY-MM-DDThh:mm:ss.sssZ) and I am trying to convert it into Wed Sep 23 09:03:46 2020. Struggling with the string manipulations, does anyone have any ideas?
Essentially my goal is to be able to perform os.time() on the date, but im aware I may need to do some reformatting beforehand.
Any help is greatly appreciated
Thanks, Scott.
local s = '2020-09-23T09:03:46.242Z'
local t = {}
t.year, t.month, t.day, t.hour, t.min, t.sec =
assert(s:match'^(%d+)%-(%d+)%-(%d+)T(%d+):(%d+):(%d+)')
print(os.date('%c', os.time(t)))
Try this:
local function convert (s)
local source_format = '(%d%d%d%d)-(%d%d)-(%d%d)T(%d%d):(%d%d):(%d%d)%.'
local year, month, day, hour, min, sec = string.match( s, source_format )
local unix_time = os.time {
year = tonumber(year),
month = tonumber(month),
day = tonumber(day),
hour = tonumber(hour),
min = tonumber(min),
sec = tonumber(sec)
}
local target_format = '%a %b %d %H:%M:%S %Y'
return os.date( target_format, unix_time )
end

Setting variable to compare file modification between multiple dates

I'm trying to compare two text files that are date specific, but I'm stumped. I created a test folder that has three text files in it with modified dates between one and 35 days old.
I.E: red.txt is 35 days old, blue.txt is one day old, and green.txt is 15 days old.
For my two compared files, the first file must be between a range of 13-15 days and the second one day old or less. So for this example, 'green.txt' will become 'file1' and 'blue.txt' will become 'file2' and then be compared with difflib, but I'm having trouble with the syntax, or maybe even the logic. I am using datetime with timedelta to try to get this working, but my results will always store the oldest modified file that is past 15 days for 'file1'. Here's my code:
import os, glob, sys, difflib, datetime as d
p_path = 'C:/test/Text_file_compare_test/'
f_list = glob.glob(os.path.join(p_path, '*.txt'))
file1 = ''
file2 = ''
min_days_ago = d.datetime.now() - d.timedelta(days=1)
max_days_ago = d.datetime.now() - d.timedelta(days=13 <= 15)
for file in f_list:
filetime = d.datetime.fromtimestamp(os.path.getmtime(file))
if filetime < max_days_ago:
file1 = file
if filetime > min_days_ago:
file2 = file
with open(file1) as f1, open(file2) as f2:
d = difflib.Differ()
result = list(d.compare(f1.readlines(), f2.readlines()))
sys.stdout.writelines(result)
I'm certain there is something wrong with code:
max_days_ago = d.datetime.now() - d.timedelta(days=13 <= 15)
Maybe I'm just not seeing something in the datetime module that's obvious. Can someone shed some light for me? Also, this is on Windows 10 Python 3.7.2. Thanks in advance!
As per my comment, your d.timedelta(days=13 <= 15) isn't quite right as you are assigning days to a boolean value of true, which will be equivalent to d.timedelta(days=1). You need to store 3 separate time points and do your 13-15 day comparison against two different dates. The code below demonstrates what you are looking for I believe:
import datetime as d
files = {
'red': d.datetime.now() - d.timedelta(days=35),
'blue': d.datetime.now() - d.timedelta(days=0, hours=12),
'green': d.datetime.now() - d.timedelta(days=14),
}
days_ago_1 = d.datetime.now() - d.timedelta(days=1)
days_ago_13 = d.datetime.now() - d.timedelta(days=13)
days_ago_15 = d.datetime.now() - d.timedelta(days=15)
file1 = None
file2 = None
for file, filetime in files.items():
if days_ago_13 >= filetime >= days_ago_15:
file1 = file
elif filetime > days_ago_1:
file2 = file
# need to break out of the loop when we are finished
if file1 and file2:
break
print(file1, file2)
prints green blue

Match an approaching date In Lua

I'm looking for a little help on a Lua script. Essentially I'm looking to match an approaching date X number of minutes prior to today. In the example below I've used 9000 minutes.
alarm.get ()
message = "Certificate Expiry Warning - Do something"
SUPPKEY = "Certificate Expiry"
SUBSYS = "1.1"
SOURCE = "SERVERNAME"
--local pattern = "(%d-%m-%Y)"
local t = os.date('*t'); -- get current date and time
print(os.date("%d-%m-%Y")); --Prints todays date
t.min = t.min - 9000; -- subtract 9000 minutes
--print(os.date("%Y-%m-%d %H:%m:%S", os.time(t))); --Original Script
print(os.date("%d-%m-%Y", os.time(t))); --Prints alerting date
if string.match ~=t.min --Match string
--if string.match(a.message, pattern)
--then print (al.message)
then print ("We have a match")
--then nimbus.alarm (1, message , SUPPKEY , SUBSYS , SOURCE) --Sends alert
else print ("Everything is fine") --Postive, no alert
--else print (al.message)
end
The alarm.get grabs a line of text that looks like this:
DOMAIN\USERNAME,Web Server (WebServer),13/01/2017 09:13,13/01/2019,COMPANY_NAME,HOSTNAME_FQDN,SITE
So the line shown above is passed as an a.message variable and I'm looking to match the date highlighted in bold to today's date with 9000 minutes taken off it.
The commented out parts are just me testing different things.
I'm not sure if I understood the question well, but from my perspective it seems you are trying to do two things:
Retrieve current time minus 9000 minutes in format DD/MM/YYYY.
Compare this time to the one your program reads from file and do something, when the two dates are equal.
Here goes my sample code:
-- Settings
local ALLOWED_AGE = 9000 -- In minutes
-- Input line (for testing only)
local inputstr = "DOMAIN\\USERNAME,Web Server (WebServer),13/01/2017 09:13,13/01/2019,COMPANY_NAME,HOSTNAME_FQDN,SITE"
-- Separate line into 7 variables by token ","
local path, server, time, date, company_name, hostname, site = string.match(inputstr, "([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+)")
-- Check, if the line is ok (not necessary, but should be here to handle possible errors)
-- Also note, some additional checks should be here (eg. regex to match DD/MM/YYYY format)
if date == nil then
print("Error reading line: "..inputstr)
end
-- Get current time minus 9000 minutes (in format DD/MM/YYYY)
local target_date = os.date("%d/%m/%Y", os.time() - ALLOWED_AGE * 60)
-- Printing what we got (for testing purposes)
print("Target date: "..target_date..", Input date: "..date)
-- Testing the match
if target_date == date then
print("Dates are matched!")
else
print("Dates are not matched!")
end
Although I'm not sure, whether you shouldn't be instead checking for "one date is bigger/smaller then the other" in your case.
Then the code above should be modified to something like this:
-- Extract day, month and year from date in format DD/MM/YYYY
local d, m, y = string.match(date, "([^/]+)/([^/]+)/([^/]+)")
-- Note I'm adding one day, so the certificate will actually expire day after it's "valid until" date.
local valid_until = os.time({year = y, month = m, day = d + 1})
local expire_time = os.time() - ALLOWED_AGE * 60 -- All certificates older than this should expire.
-- Printing what we got (for testing purposes)
print("Expire time: "..expire_time..", Cert valid until: "..valid_until)
-- Is expired?
if valid_until <= expire_time then
print("Oops! Certificate expired.")
else
print("Certificate date is valid.")
end

Insert rows into Excel with MATLAB

The data in my Excel files is supposed to be contentious (index in the first column). But some data is missing in the file. For example, # 5, and 6 are missing between $ 4 and 7. My purpose are (1) identify the file with missing data and (2) if data is missing insert rows to make it continuous. Can anyone tell me how to add in rows in the existing data? Using xlswrite I can only add in rows at the end of the file or replace some rows.
EDIT 1:
I have another set of file in which the index is not so direct. The first 3 columns are described below (as shown in the Excel file):
Column 1:Year: 2003 (read as number in matlab)
Column 2:Date: 1-Sep (read as text in matlab)
Column 3:Time: 1:00 (1:00 read as number 0.04167 and 2:00 read as 0.0833, not sure how it works)
Then the way to tell if it is continuous will be quite complicate since there will be different years, months, and days. Could you give some hint on this?
Basically you need to read the entire data, preferably in raw(cell) format, add the missing rows(with respect to the indices) and write back.
Based on your question, this code might work -
% NOTE: We are assuming that the indexing starts with 1
% Read data from input excel file with missing indices
[num,txt,raw] = xlsread('input.xls');
% Error-checking
if (size(num,1)-num(end,1)~=0)
disp('At least one index is missing!');
end
% Expand data such that all indices are covered.
data1=NaN(num(end,1),size(raw,2));
data1(:,1) = 1:num(end,1);
data1=num2cell(data1);
k1=1;
for k = 1:num(end,1)
if(num(k1,1)==k)
data1(k,:)= raw(k1,:);
k1 = k1+1;
end
end
% Write data
xlswrite('output.xls',data1);
EDIT 1:
In view of your new requirements, additional code is added next.
Please note few things about this code -
The code adds data for every year and not from a specific month, date and time to another specific month, date and time. If you wish to achieve that, please edit the associated
function - 'create_comp_sheet'.
It saves an intermediate file named - 'proper_base_data.xls', which maybe deleted at the end of the code.
%% MAIN CODE - CODE1.M
INPUT_FILENAME = 'input.xls'; % Excel file that has some missing year,date and time info
OUTPUT_FILENAME = 'output.xls'; % Excel file that has data from the input file along with all the missing year,date and time info
%% Base data
start_year=2003;
end_year=2005;
proper_base_data = create_comp_sheet(start_year,end_year);
xlswrite('proper_base_data.xls',proper_base_data);
[num,txt,raw] = xlsread('proper_base_data.xls');
base_data=cell(size(num,1),1);
for row_ID = 1:size(num,1)
base_data(row_ID) = {strcat(num2str(cell2mat(raw(row_ID,1))),'-', cell2mat(raw(row_ID,2)),'-',num2str(round(24*cell2mat(raw(row_ID,3)))))};
end
%% Input data
[num,txt,raw] = xlsread(INPUT_FILENAME);
input_data=cell(size(num,1),1);
for row_ID = 1:size(num,1)
input_data(row_ID) = {strcat(num2str(cell2mat(raw(row_ID,1))),'-', cell2mat(raw(row_ID,2)),'-',num2str(round(24*cell2mat(raw(row_ID,3)))))};
end
%% Setup final data
final_data = num2cell(NaN(size(proper_base_data,1),size(raw,2)));
final_data(:,1:3) = proper_base_data;
for k1=1:size(input_data,1)
for k2=1:size(base_data,1)
if strcmp(cell2mat(base_data(k2)),cell2mat(input_data(k1)))
final_data(k2,4:end) = raw(k1,4:end);
end
end
end
%% Write final data to excel
xlswrite(OUTPUT_FILENAME,final_data);
Associated function -
function data1 = create_comp_sheet(start_year,end_year)
months_string = {'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'};
date_count = [31 28 31 30 31 30 31 31 30 31 30 31];
num_hours = 24;
data1=[];
for year_ID = start_year:end_year
for month_ID = 1:numel(months_string)
days_per_month = date_count(month_ID);
if rem(year_ID,4)==0 && month_ID ==2
days_per_month = days_per_month+1;
end
for date_ID = 1:days_per_month
year = repmat({num2str(year_ID)},[num_hours 1]);
date = repmat({strcat(num2str(date_ID),'-',char(months_string(month_ID)))},[num_hours 1]);
time=cell(num_hours,1);
for k = 1:num_hours
time(k) = {strcat(num2str(k),':00')};
end
data1 = [data1 ; [year date time]];
end
end
end
return;
Hope this saves all your troubles!

Resources