Master Python Time Handling: datetime, time, and calendar Explained
This article provides a concise overview of Python's three core time modules—datetime, time, and calendar—explaining their design, key concepts like epoch, UTC, DST, and demonstrating how to obtain, convert, and manipulate dates and times with practical code examples.
1. Overview
The datetime module represents full date‑time information (year, month, day, hour, minute, second). The calendar module focuses on calendar‑related data such as year, month, day, and weekday. The time module deals mainly with seconds and fractions of a second. Together they complement each other, allowing developers to choose the most suitable module for a given task.
2. Starting with the time module
(1) epoch
Unix time counts seconds from the epoch, which is 00:00:00 UTC on 1 January 1970. All timestamps are measured relative to this point.
(2) GMT, UTC
GMT (Greenwich Mean Time) is the historic reference; UTC (Coordinated Universal Time) is the modern standard based on atomic clocks. UTC is the true baseline; GMT is effectively UTC + 0.
(3) DST, timezone
Daylight Saving Time (DST) adjusts clocks to make better use of daylight. Timezone information (often stored in the TZ environment variable on Linux) tells the system how to convert between local time and UTC.
(4) Representing, obtaining, converting time
Basic retrieval of the current timestamp: t = time.time() This returns the number of seconds (as a float) since the epoch, using UTC.
Conversion to a structured struct_time object:
time.gmtime(t) time.localtime(t)Both functions return a struct_time instance with attributes such as tm_year, tm_mon, tm_mday, etc.
Reverse conversion:
calendar.timegm(struct_time) time.mktime(struct_time)String formatting and parsing:
time.strftime(format, struct_time) time.strptime(string, format)Convenient helpers:
time.asctime(struct_time) time.ctime(seconds)localtime
) -->
3. datetime module
(1) Overview
While time handles timestamps, datetime provides classes for direct manipulation of dates and times. The three core classes are date (year‑month‑day), time (hour‑minute‑second‑microsecond), and datetime (a combination of both).
(2) Creating datetime objects
Common ways to obtain a datetime instance: dt = datetime.datetime.fromtimestamp(time.time()) The result is local time by default. To create UTC datetime:
datetime.datetime.utcfromtimestamp(time.time()) datetime.datetime.utcnow()Convenient shortcuts for the current local datetime:
datetime.datetime.now() datetime.datetime.today()Parsing from a string: datetime.datetime.strptime(date_string, format) Formatting back to a string uses the same strftime method as the time module.
(3) Creating date and time objects
Creating a date:
datetime.date.today() datetime.date.fromtimestamp(seconds)Creating a time object (only time‑of‑day, no date):
datetime.time([hour[, minute[, second[, microsecond[, tzinfo]]]]])(4) Operations with timedelta
Arithmetic between date or datetime objects yields a timedelta representing the difference. You can also add or subtract a timedelta to shift a date or datetime. timedelta attributes: days (can be negative), seconds, microseconds. Use total_seconds() to get the full duration in seconds. timedelta objects support addition, subtraction, multiplication, floor division, negation, and abs().
4. No summary, no progress
The goal of this article is not to provide exhaustive API documentation, but to give a high‑level overview of the design and capabilities of Python's time and datetime modules so that developers can recall and apply the appropriate functions 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.
