Python code snippits

Date and time

Convert Python datetime to a string, and vice verse

import datetime

def timestamp():
    return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

def parse_timestamp(t):
    return datetime.datetime.strptime(t, '%Y-%m-%d %H:%M:%S')

Email

Send email through Outlook

import win32com.client

def send_email(to,cc,subject,body):
    outlook = win32com.client.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = to
    mail.Subject = subject
    mail.HTMLBody = body
    mail.cc = cc
    mail.Display()
    #mail.Send()

Files

Find the path of my script

import os.path

file_path = os.path.dirname(os.path.realpath(__file__))

CSV

Read a CSV file

import chardet
import csv,codecs

def readCSV(file):
    output = []
    # -- detect the file encoding first
    with open(file, 'rb') as f:
        result = chardet.detect(f.read())  

    with open(file, 'rb') as csvfile:       
        # = read the file line by line
        reader = csv.DictReader(codecs.iterdecode(csvfile, result['encoding']))
        for row in reader:
            output.append(row)

    return output

if __name__ == '__main__':
    for x in readCSV('c:/temp/test.csv'):
        print(x)

Slack or Discord

Sending messages via Slack or Discord

import json
import urllib.request
import urllib.parse

def slackdiscord(webHook,message):
    if 'discord' in webHook:
        msg = { 'content' : message }
    else:
        msg = { 'text' : message }
    req = urllib.request.Request(
        webHook,
        json.dumps(msg).encode('utf-8'),
        {   
            'Content-Type': 'application/json',
            'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11'
        }
    )
    resp = urllib.request.urlopen(req)
    return resp.read()

Web monitoring

import urllib.request

def website_monitor(url):
    #print(f'URL : {url}')
    try:
        req = urllib.request.Request(url, method='HEAD')
        resp = urllib.request.urlopen(req, timeout=10)
        #print(resp.getcode())
        return resp.getcode() == 200
    except:
        return False
    return False