Book Image

Modern Python Standard Library Cookbook

By : Alessandro Molina
Book Image

Modern Python Standard Library Cookbook

By: Alessandro Molina

Overview of this book

The Python 3 Standard Library is a vast array of modules that you can use for developing various kinds of applications. It contains an exhaustive list of libraries, and this book will help you choose the best one to address specific programming problems in Python. The Modern Python Standard Library Cookbook begins with recipes on containers and data structures and guides you in performing effective text management in Python. You will find Python recipes for command-line operations, networking, filesystems and directories, and concurrent execution. You will learn about Python security essentials in Python and get to grips with various development tools for debugging, benchmarking, inspection, error reporting, and tracing. The book includes recipes to help you create graphical user interfaces for your application. You will learn to work with multimedia components and perform mathematical operations on date and time. The recipes will also show you how to deploy different searching and sorting algorithms on your data. By the end of the book, you will have acquired the skills needed to write clean code in Python and develop applications that meet your needs.
Table of Contents (21 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Index

Parsing dates


When receiving a datetime from another software or from a user, it will probably be in a string format. Formats such as JSON don't even define how a date should be represented, but it's usually a best practice to provide those in the ISO 8601 format.

The ISO 8601 format is usually defined as [YYYY]-[MM]-[DD]T[hh]:[mm]:[ss]+-[TZ], for example 2018-03-19T22:00+0100 would refer to March 19 at 10 P.M. on the UTC+01:00 time zone.

ISO 8601 conveys all the information you need to represent a date and time, so it's a good way to marshal a datetime and send it across a network.

Sadly, it has many oddities (for example, the +00 time zone can also be written as Z, or you can omit the : between hours, minutes, and seconds), so parsing it might sometimes cause trouble.

How to do it...

Here are the steps to follow:

  1. Due to all the variants ISO 8601 allows, there is no easy way to throw it to datetime.datetime.strptime and get back a datetime for all case; we must coalesce all possible formats to...