Overview Handling time is one of the most deceptively complex tasks in software development. Between leap years, shifting time zones, and the chaotic history of daylight savings, what seems like a simple integer is actually a political and geographical mess. In Python, we have several ways to tame this chaos. This guide explores the standard `datetime` module and the powerful Pendulum library to help you write robust, time-aware applications. Prerequisites To follow along, you should have a basic understanding of Python syntax and how to install packages using `pip`. Familiarity with object-oriented concepts like classes and methods will help you understand how date objects interact. Key Libraries & Tools * **datetime**: The built-in Python module for basic date and time manipulation. * **time**: A standard library used for low-level time functions, including Unix timestamps. * **pytz**: The standard library for world time zone definitions (requires installation). * **Pendulum**: A third-party library that provides a cleaner, more intuitive API for complex time operations. Understanding Unix Time and UTC Computers generally view time as a linear progression of seconds from a fixed point. This is known as Unix time, starting from the Unix Epoch: January 1st, 1970, at 00:00:00 UTC. ```python import time Get the current Unix timestamp as a float print(time.time()) Get nanosecond precision as an integer print(time.time_ns()) ``` UTC acts as our "z-time" or Zulu time. It never adjusts for daylight savings, making it the ideal standard for database storage and system logs. Working with the Datetime Module Python’s built-in `datetime` class is our primary tool for human-readable dates. ```python from datetime import datetime Creating a specific date some_date = datetime(2022, 9, 16, 6, 0) Parsing from ISO 8601 strings iso_date = datetime.from_isoformat("2022-09-16 14:05:13") Getting current local time now = datetime.now() ``` By default, these objects are **naive**, meaning they lack time zone information. To make them **aware**, we use pytz. ```python from pytz import timezone utc = timezone('UTC') sydney = timezone('Australia/Sydney') Localize a naive date to UTC localized_date = utc.localize(some_date) Convert to another zone sydney_time = localized_date.astimezone(sydney) ``` Simplifying Time with Pendulum While the standard library is capable, it can be verbose. Pendulum simplifies this by making objects time-zone aware by default and providing "human" features. ```python import pendulum Cleaner creation and timezone handling now = pendulum.now('UTC') sydney_time = now.in_timezone('Australia/Sydney') Human-readable differences future = now.add(years=1) print(future.diff_for_humans()) # "in 1 year" Localization print(now.format('dddd DD MMMM YYYY', locale='de')) # Prints in German ``` Syntax Notes * **ISO 8601**: The standard string format (YYYY-MM-DD) supported by `from_isoformat()`. * **tzinfo**: The property on a datetime object that determines if it is "naive" (None) or "aware." * **Method Chaining**: Pendulum allows chaining like `.add(days=1).in_timezone('UTC')`. Tips & Gotchas * **The 2038 Problem**: Older 32-bit systems will overflow their signed integers on January 19, 2038. Ensure your production environments run on 64-bit architectures. * **Storage Best Practice**: Always store dates in UTC in your database. Only convert to local time zones at the very last moment when displaying data to the user. * **Maintenance Risk**: Pendulum is excellent, but check its maintenance status before including it in critical enterprise projects. If your needs are simple, the built-in `datetime` is often safer.
ISO 8601
Products
Oct 2022 • 1 videos
High activity month for ISO 8601. ArjanCodes among the most active voices, with 1 videos across 1 sources.
Oct 2022
- Oct 14, 2022