Comprehensive Guide to Python Time Handling Modules (time, datetime, pytz, dateutil, Arrow, ISO 8601)
This article provides a thorough overview of Python's time‑related libraries—including the built‑in time and datetime modules, third‑party pytz, dateutil, and Arrow—explaining core concepts such as timestamps, time zones, daylight‑saving time, and ISO 8601 parsing with clear code examples and usage patterns.
Time‑Related Concepts
The second is defined by the 13th CGPM in 1967 as 9,192,631,770 periods of the radiation corresponding to the transition between two hyperfine levels of the ground state of the cesium‑133 atom; the epoch starts at 1970‑01‑01 00:00:00 UTC.
GMT (Greenwich Mean Time) is the standard time at the Royal Observatory in Greenwich, also known as UT (Universal Time). UTC (Coordinated Universal Time) is based on atomic clocks and kept within 0.9 seconds of UT.
A leap second is occasionally added or subtracted to keep UTC within ±0.9 seconds of UT, due to irregularities in Earth's rotation.
Time zones divide the Earth into 24 regions, each offset by an integer number of hours from UTC; for example, China uses GMT+8.
Daylight Saving Time (DST) shifts clocks forward by one hour during summer to save energy.
The Unix timestamp counts seconds elapsed since 1970‑01‑01 00:00:00 UTC, ignoring leap seconds.
Python time Module
The time module provides OS‑level time functions centered on Unix timestamps. It defines the struct_time tuple (9 elements: year, month, day, hour, minute, second, weekday, yearday, isdst).
time() – current timestamp.
ctime([secs]) – string representation.
asctime([struct]) – string from struct_time .
localtime([secs]) – struct_time in local zone.
gmtime([secs]) – struct_time in UTC.
<code>import time
print(time.time())
print(time.ctime())
print(time.localtime())
print(time.gmtime())
</code>Formatting and parsing use time.strftime(format, t) and time.strptime(string, format) . The format specifiers include %Y , %m , %d , %H , %M , %S , etc.
<code>>>> time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
'2023-08-15 14:23:41'
</code>Timer functions: time.sleep(secs) pauses execution; time.clock() returns processor time (platform‑dependent).
Python datetime Module
The datetime module builds on time and offers richer classes:
date – year, month, day.
time – hour, minute, second, microsecond, optional tzinfo.
datetime – combination of date and time.
timedelta – duration between two dates/times.
tzinfo – abstract base for time‑zone information.
Key class methods include date.today() , datetime.now([tz]) , datetime.utcnow() , datetime.fromtimestamp(ts, tz=None) , and datetime.combine(date, time) . Instances support .isoformat() , .strftime() , arithmetic with timedelta , and comparison operators.
<code>from datetime import datetime, date, timedelta
print(datetime.now())
print(date.today())
print(datetime.utcnow())
print(datetime.fromtimestamp(time.time()))
print(datetime.now() + timedelta(days=5))
</code>Third‑Party Time Libraries
pytz
pytz supplies the Olson TZ database, enabling reliable time‑zone conversions and proper DST handling.
<code>import pytz, datetime
tz = pytz.timezone('Asia/Shanghai')
now = datetime.datetime.now(tz)
print(now)
print(now.astimezone(pytz.utc))
</code>Country‑specific zones can be queried with pytz.country_timezones('cn') , returning ['Asia/Shanghai', 'Asia/Urumqi'] .
dateutil
The dateutil package provides flexible parsing ( parser.parse() ) and recurrence rules ( rrule ).
<code>from dateutil import parser
print(parser.parse('8th March, 2004'))
</code>Arrow
Arrow offers a friendly API for creating, shifting, and formatting dates, handling time zones, and human‑readable output.
<code>import arrow
now = arrow.now()
print(now)
print(now.shift(hours=5).humanize())
print(now.to('US/Pacific'))
</code>ISO 8601
ISO 8601 strings can be parsed with dateutil.parser or datetime.strptime using patterns such as "%Y-%m-%dT%H:%M:%S.%fZ" . The iso8601 module is another option.
Other Utilities
Libraries like pendulum , delorean , freezegun , and workalendar provide additional features such as human‑friendly dates, time‑travel for testing, and holiday calendars.
Summary
This guide consolidates essential knowledge for handling dates and times in Python, covering built‑in modules, third‑party libraries, time‑zone intricacies, DST, and ISO 8601 standards, with practical code snippets to help developers write robust, portable time‑aware applications.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.