Master Python Time Handling: datetime, time, and calendar Explained
This article provides a comprehensive overview of Python's time‑related modules—datetime, time, and calendar—explaining their design, key concepts like epoch, UTC, DST, and practical APIs for obtaining, converting, and manipulating dates and times.
1. Overview
The datetime module represents full date‑time (year, month, day, hour, minute, second), calendar focuses on calendar‑related information (year, month, weekday), and time deals mainly with seconds, minutes, and hours. Together they complement each other, letting users choose the most suitable module for a given task.
2. Starting with the time module
Key time‑related concepts:
(1) epoch
Epoch is the reference point for Unix timestamps; in Unix it is 1970‑01‑01 00:00:00 UTC. All timestamps are measured as seconds (or fractions) since this point.
(2) GMT, 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.
(3) DST, tzone
Daylight Saving Time (DST) and time zones (tzone) adjust clock time based on regional policies. In Linux, the TZ environment variable (e.g., CST+08EDT,M4.1.0,M10.5.0) encodes the base zone, DST name, and start/end rules.
(4) Getting and converting time
Basic retrieval: t = time.time() # seconds since epoch (UTC)
Conversion to struct_time: time.gmtime(t) # UTC struct_time time.localtime(t) # local‑zone struct_time
Both return a struct_time object with attributes such as tm_year, tm_mon, etc.
Reverse conversion: calendar.timegm(struct_time) # struct_time → epoch seconds (UTC) time.mktime(struct_time) # struct_time → epoch seconds (local, applying zone/DST)
String formatting and parsing: time.strftime(format, struct_time) # struct_time → formatted string time.strptime(string, format) # string → struct_time
Convenient helpers: time.asctime(struct_time) # struct_time → 24‑char string time.ctime(seconds) # seconds → string (via localtime then asctime)
These functions form the core of the time module.
3. datetime module
(1) Overview
The datetime module builds on time to provide easy access to year, month, day, hour, minute, second, and microsecond components. Its three main classes are date (year‑month‑day), time (hour‑minute‑second‑microsecond), and datetime (combination of both).
Both datetime and time objects have a tzinfo attribute; when set, the object is “aware” and can be accurately converted to epoch seconds. If tzinfo is None, the object is “naive” and its zone must be interpreted manually.
(2) Creating datetime objects
Common ways to obtain a datetime instance: dt = datetime.datetime.fromtimestamp(time.time()) # local time from epoch seconds datetime.datetime.now() or datetime.datetime.today() # current local datetime datetime.datetime.utcfromtimestamp(seconds) # UTC datetime from epoch seconds datetime.datetime.utcnow() # current UTC datetime
Parsing from a string: datetime.datetime.strptime(date_string, format) Formatting to a string: datetime.datetime.strftime(format) Combining a date and a time into a datetime:
datetime.datetime.combine(date_obj, time_obj)(3) date and time creation
datetime.date.today()or datetime.date.fromtimestamp(seconds) create date objects.
datetime.time([hour[, minute[, second[, microsecond[, tzinfo]]]]])creates a time object.
(4) Operations and timedelta
Arithmetic and comparison are supported between date or datetime objects. Subtracting two dates yields a timedelta representing the difference (days, seconds, microseconds). Adding or subtracting a timedelta adjusts the date/datetime. timedelta attributes: days (can be negative), seconds, microseconds. Methods like total_seconds() return the full duration in seconds. timedelta can be multiplied or divided by integers, negated, or passed to abs().
4. No summary, no progress
The goal of this article is not to list every API in detail, but to give a high‑level map of Python's time‑handling modules so readers can recall the right tools when needed and locate the exact documentation quickly.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
