Fundamentals 13 min read

Master Python Time Handling: datetime, time, and calendar Essentials

This article provides a comprehensive overview of Python's three core time modules—datetime, time, and calendar—explaining their design, key concepts like epoch, UTC, DST, and demonstrating essential APIs for retrieving, converting, and manipulating dates and times.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Time Handling: datetime, time, and calendar Essentials

Python offers three built‑in modules for working with dates and times: datetime, time, and calendar. Understanding their design helps you choose the right API for a given task.

1. Overview

The datetime module represents full timestamps (year, month, day, hour, minute, second). The calendar module focuses on calendar‑related information (year, month, day, weekday). The time module deals mainly with seconds since the epoch. Together they form a complementary set.

2. Starting with the time module

2.1 Epoch

The epoch is the reference point for Unix timestamps: 1970‑01‑01 00:00:00 UTC. All timestamps are counted as seconds (or fractions) from this moment.

2.2 GMT and UTC

GMT (Greenwich Mean Time) is the historic time standard, while UTC (Coordinated Universal Time) is the modern atomic‑clock‑based standard. UTC is the true reference; GMT is effectively UTC with a zero offset.

2.3 DST and Time Zones

Daylight Saving Time (DST) adjusts clocks to make better use of daylight. Time‑zone information and DST rules are obtained from the operating system’s environment variables (e.g., the TZ variable on Linux). CST+08EDT,M4.1.0,M10.5.0 In the example above, CST denotes China Standard Time (UTC+8). EDT is the DST name; the DST rules are omitted for brevity.

2.4 Getting and converting timestamps

Retrieve the current timestamp (seconds since the epoch): t = time.time() Convert a timestamp to a struct_time in UTC or local time:

time.gmtime(t)
time.localtime(t)

Both functions return a struct_time object whose attributes are shown in the following table:

Convert a struct_time back to a timestamp: calendar.timegm(gmtime_struct) Convert a local struct_time (with time‑zone adjustment) back to a timestamp: time.mktime(localtime_struct) Format a struct_time as a string or parse a string into a struct_time using strftime and strptime:

time.strftime(format, struct_time)
time.strptime(date_string, format)

Convenient helpers for string conversion are asctime and ctime:

asctime(struct_time)   # e.g., Sun Jun 20 23:21:05 1993
ctime(timestamp)       # converts timestamp to struct_time then asctime

3. The datetime module

3.1 Overview

The datetime module builds on time to provide easy access to year, month, day, hour, minute, second, and microsecond. Its three core classes are date, time, and datetime (a combination of date and time).

3.2 Creating datetime objects

From a timestamp:

dt = datetime.datetime.fromtimestamp(time.time())

This yields a *local* datetime. To obtain a UTC datetime, use:

datetime.datetime.utcfromtimestamp(timestamp)
datetime.datetime.utcnow()

Parse a string into a datetime: datetime.strptime(date_string, format) Other useful constructors are datetime.now() and datetime.today(), both returning local datetimes.

3.3 Creating date and time objects

Typical ways to create a date:

datetime.date.today()
datetime.date.fromtimestamp(timestamp)

Or directly via the constructor: datetime.date(year, month, day) Creating a time object is more limited:

datetime.time([hour[, minute[, second[, microsecond[, tzinfo]]]]])

3.4 Arithmetic with date , datetime and timedelta

Both date and datetime support comparison operators and subtraction, which produce a timedelta object. Adding or subtracting a timedelta adjusts the original date or datetime.

A timedelta stores days, seconds, and microseconds. The total number of seconds can be obtained via timedelta.total_seconds(). timedelta objects can be multiplied or divided by integers, and their absolute value can be taken with abs().

4. Conclusion

The goal of this article is not to detail every API call but to give a clear mental model of how the time and datetime modules are organized, so you can quickly recall the right functions when needed.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythondatetimetimestampTimezonedate handlingtime moduletimedelta
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.