How to get the current date and time in Python

Getting the current time is one line. Getting a value that still means something tomorrow, on another machine, in another timezone, takes a little more thought. This article covers both.

How to iterate over rows in a Pandas DataFrame

pandas is the standard library for tabular data in Python. It offers several ways to walk a DataFrame row by row, and the usual advice is not to. This article shows the ways, what each one costs, and the two behaviours that surprise people.

How to merge two dictionaries in Python

Merging two dictionaries used to take two statements. Since Python 3.9 it takes one character. This article shows the options, and the one property of all of them that causes trouble in real code.

How to pass a variable by reference in Python

Python has neither pass-by-value nor pass-by-reference, and the usual explanation — “mutable types are passed by reference, immutable ones by value” — is close enough to sound right and wrong enough to mislead. This article takes it apart.

How to rename columns in a Pandas DataFrame

Renaming columns is usually the first thing you do after reading somebody else’s CSV. There are two main ways, they behave differently when you get it wrong, and one of them fails without telling you.

How to run a program or system command from Python

Sooner or later a Python script has to call something else — git, ffmpeg, pg_dump. This article shows how to do that with subprocess.run(), and demonstrates what the warnings about shell=True are actually about.

How to sort a dictionary by value in Python

Sorting a dictionary by value is a one-liner. Getting the ties right, and mixing ascending and descending in the same sort, is where it gets interesting.

How to split a list into equally-sized chunks in Python

Batching a list comes up constantly — API calls that take 100 IDs at a time, database inserts, rate limits. Since Python 3.12 the standard library has a function for it, and most of the answers you will find online predate it.

How to upgrade all Python packages with pip

pip is the package installer for Python. It has no upgrade-all command, so everybody copies a shell one-liner from somewhere. This article shows the better version, and demonstrates the failure the one-liners can leave behind.

How to use a global variable in a Python function

Reading a module-level variable inside a function needs nothing at all. Assigning to one needs the global keyword — and the error you get without it points at the wrong line, which is what makes this confusing.