Mastering Date and Time in Python: From Standard Library to Pendulum
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 library to help you write robust, time-aware applications.
Prerequisites
To follow along, you should have a basic understanding of 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 , starting from the Unix Epoch: January 1st, 1970, at 00:00:00 .
import time
# Get the current Unix timestamp as a float
print(time.time())
# Get nanosecond precision as an integer
print(time.time_ns())
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.
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 .
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. simplifies this by making objects time-zone aware by default and providing "human" features.
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: 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 in your database. Only convert to local time zones at the very last moment when displaying data to the user.
- Maintenance Risk: is excellent, but check its maintenance status before including it in critical enterprise projects. If your needs are simple, the built-in
datetimeis often safer.
- 36%· products
- 27%· products
- 9%· products
- 9%· products
- 9%· products
- 9%· products

A Deep Dive Into Date And Time In Python
WatchArjanCodes // 19:39
On this channel, I post videos about programming and software design to help you take your coding skills to the next level. I'm an entrepreneur and a university lecturer in computer science, with more than 20 years of experience in software development and design. If you're a software developer and you want to improve your development skills, and learn more about programming in general, make sure to subscribe for helpful videos. I post a video here every Friday. If you have any suggestion for a topic you'd like me to cover, just leave a comment on any of my videos and I'll take it under consideration. Thanks for watching!