Friday, May 15, 2020

Python Convert 12 Hour to 24 Hour Time

For computation purposes, 24 hour time works better. Here is a function to convert the 12 Hour time String to 24 hour time string.
def time_convert_12_24(self,str_time):
    
    time_arr = str_time.split()  # split by space    n = time_arr[0].count(':')
    time_str : str ='' 
    if n == 1 :
       #5:30        
       time_str = time_arr[0]+':00'     
    elif n == 0 :
       #5 
       time_str = time_arr[0]+':00:00'     
    else :
       time_str = time_arr[0]
    #change 12:00 am to 00:00
    if time_arr[1].upper() == 'AM' and time_str[:1] == "12":
        "00" + time_str[2:-2]
    # add 12 hour to PM hours
    if time_arr[1].upper() == 'PM' :
        str_part = time_str.split(':')
        if int(str_part[0]) != 12 :
            return str(int(str_part[0]) + 12) +':'+str_part[1] + ':'+ str_part[2]
        else :
            return time_str
    else :
        return time_str

Thursday, May 14, 2020

Substitute Variables in PostgreSQL

It is useful to use variables in a SQL script. For example, when writing a create objects script, we can use a variable to store the schema name. This way, if we decide to change the schema name later, we just need to re-set the value for the variable.

\set dm_schema 'dm'
CREATE SCHEMA IF NOT EXISTS :dm_schema;

create table IF NOT EXISTS :dm_schema.user(
    user_id                          serial primary key,
    user_name                        VARCHAR(128),
    user_email                       VARCHAR(128)
  
);

create table IF NOT EXISTS :dm_schema.use_groupr(
   group_id                          serial primary key,
   group_name                        VARCHAR(128)
  
);

Wednesday, April 01, 2020

Added A Column To Every Table In The Same Schema In PostgresSQL

Sometime, we may find out that we need to add a column to every table in the same schema or same database. For example, we want to add an audit column. The following query is for that.


do $$
declare
    addcolumn record;
    dm_schema VARCHAR(8) := ‘sales_dm';
begin
for addcolumn in
select
      'ALTER TABLE '|| dm_schema ||'.'|| T.targettable ||  ' ADD COLUMN  IF NOT EXISTS last_modified_timestamp timestamp  NULL' as sqlscript
   from
      (
        select tablename as targettable from  pg_tables where schemaname = dm_schema 
      ) t
loop
execute addcolumn.sqlscript;
end loop;
end;
$$;