Master Python’s time, datetime, and calendar Modules: A Complete Guide
This article provides a comprehensive overview of Python’s three core time-handling modules—time, datetime, and calendar—explaining key concepts such as epoch, UTC/GMT, time zones, DST, and demonstrating how to retrieve, format, and convert dates and times using their APIs.
1. Overview
The datetime module represents full date and time (year, month, day, hour, minute, second). The calendar module focuses on calendar information such as year, month, day, and weekday. The time module concentrates on seconds, minutes, and hours. Together they complement each other, allowing developers to choose the most suitable module for a given task.
2. The time Module
(1) Epoch
Epoch is the reference point for Unix timestamps, defined as 00:00:00 UTC on 1 January 1970. All timestamps are measured as seconds elapsed since this point.
(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.
(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 environment variables, e.g., the TZ variable on Linux (e.g., CST+08EDT,M4.1.0,M10.5.0).
(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‑time struct_time
Both return a struct_time object. Converting back: calendar.timegm(struct_time) # struct_time (UTC) → timestamp time.mktime(struct_time) # struct_time (local) → timestamp
Formatting and parsing strings: 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‑character string time.ctime(timestamp) # timestamp → string (via localtime)
3. The datetime Module
(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 (year‑month‑day), time (hour‑minute‑second‑microsecond), and datetime (combination of both).
Both datetime and time have a tzinfo attribute that makes an object “aware” of its time zone; if tzinfo is None, the object is “naive”.
(2) Creating datetime Objects
Common ways: dt = datetime.datetime.fromtimestamp(time.time()) # local datetime from timestamp datetime.datetime.now() # current local datetime datetime.datetime.today() # same as now()
UTC equivalents:
datetime.datetime.utcfromtimestamp(timestamp) datetime.datetime.utcnow()From string: datetime.datetime.strptime(date_string, format) Formatting: datetime.datetime.strftime(format) Other utilities: datetime.datetime.combine(date_obj, time_obj) # merge date and time
(3) Creating date and time Objects
datetime.date.today()or datetime.date.fromtimestamp(timestamp) create date objects.
datetime.time([hour[, minute[, second[, microsecond[, tzinfo]]]]])creates a time object.
(4) Arithmetic with timedelta
Subtracting two date or two datetime objects yields a timedelta (attributes: days, seconds, microseconds). You can add or subtract a timedelta to/from a date / datetime. timedelta.total_seconds() returns the total seconds.
Operations such as multiplication or floor division with integers are also supported.
4. No Summary, No Progress
The goal of this article is not to detail every API call, but to give a high‑level map of the time and datetime modules so readers can recall their capabilities and know where to look when needed.
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.
