Python Cheat Sheet

This a cheatsheet for how to implement different stuff in Python. I found those instructions helpful for me, while I was writing some scripts to parse some CSV, or to deploy some Lambda functions on AWS.

Let's start:

Date/Time Objects

Getting current time object

import datetime
now = datetime.datetime.now()
print(now.isoformat())
past = now - datetime.timedelta(hours=5)

Print/Parsing a Date in ISO Format

from datetime import date
date_object = date.today()
print(date_object.strftime("%b")) # Printing the Month. For example 'May'
print(date_object.strftime("%Y-%m-%d")) # Printing the date in ISO Format
print(date_object.isoformat()) # Also gives the ISO Format

date_object = date.fromisoformat("2020-06-09") # Parsing something like '2020-06-09'
date_object = date(2020, 5, 23) # Creating a new Date Object

Adding/Subtracting Periods of Date

date.today() + datetime.timedelta(days=-5)

Parsing CSV files

from glob import glob
import csv

files = glob("*.csv")
for file_path in files:
    with open(file_path, newline="") as csvfile:
        reader = csv.reader(csvfile, delimiter=',', quotechar='"')
        next(reader) # Skip the first
        for row in reader:
          print(row)

AWS Lambda Function

AWS Lambda Python Template

import json

def lambda_handler(event, context):
  return { 'statusCode': '200', 'body': 'Hello World!', 'header': {'Content-Type': 'application/json'} }

I will expand on this section later

Deploying a Lambda function with some PIP Packages

How to deploy a Python Lambda Function to AWS with some PIP Packages Let's assume you have a Lambda function already with the name test. You can update it using the following

pip3 install --target ./package pyjwt
cd package
zip -r package.zip ./*
zip -g package.zip lambda_function.py
aws lambda update-function-code --function-name test --zip-file fileb://package.zip

Sorting in Python

Please see this Post Sorting in Python


Homepage