Master Python’s Time and Date Modules: From time to datetime, pytz, and Arrow
This comprehensive guide walks you through Python’s time‑handling ecosystem, covering the low‑level time module, the richer datetime module, timezone utilities like pytz, advanced parsing with dateutil, and the user‑friendly Arrow library, complete with explanations, code snippets, and practical examples for formatting, conversion, and manipulation.
Time‑Related Concepts
Second The international standard unit of time was defined at the 13th General Conference on Weights and Measures in 1967 as the duration of 9,192,631,770 periods of radiation corresponding to the transition between two hyperfine levels of the ground state of the cesium‑133 atom, with the epoch starting at 00:00 on 1 January 1958.
GMT Greenwich Mean Time is the standard time at the Royal Greenwich Observatory in London, named after the Prime Meridian that passes through the observatory. It is also referred to as Universal Time (UT).
UTC Coordinated Universal Time, also called world standard time, is based on international atomic clocks with an error of only a few nanoseconds per day. Its second length matches that of atomic time, and its clock time is kept within 0.9 seconds of UT.
Leap Second To keep UTC within ±0.9 seconds of UT, the International Bureau of Weights and Measures may add or subtract one second at the end of a year or mid‑year (sometimes at the end of a quarter). This adjustment compensates for irregularities and the long‑term slowdown of Earth’s rotation, mainly caused by tidal friction.
Time Zone The Earth is divided into 24 zones, each offset by one hour from its neighbours. When crossing a zone, clocks are adjusted by one hour (subtract when moving west, add when moving east). For example, China uses GMT+8.
Daylight Saving Time (DST) DST is a seasonal adjustment that moves clocks forward by one hour during summer to make better use of daylight and save energy.
Unix Timestamp The total number of seconds elapsed since 00:00:00 UTC on 1 January 1970, not counting leap seconds.
Python time Module
In the Python documentation, time is classified under Generic Operating System Services, meaning its functions operate close to the OS layer and revolve around Unix timestamps.
The module mainly provides the struct_time class and several functions and constants. Most functions are thin wrappers around the platform C library, so their behavior may differ across operating systems. Because it is based on Unix timestamps, the representable date range is limited to 1970‑2038; for dates outside this range, the datetime module is preferable.
Getting the current time and converting formats
time() returns the current time as a Unix timestamp (seconds since 1 Jan 1970 00:00:00).
ctime() returns a string representation; you can pass a timestamp to convert it.
asctime() returns a string representation of a struct_time value.
localtime() returns the current local time as a struct_time; you can also pass a timestamp.
gmtime() returns the current UTC time as a struct_time; you can also pass a timestamp.
>>> import time
>>> time.time()
1473386416.954
>>> time.ctime()
'Fri Sep 09 10:00:25 2016'
>>> time.ctime(time.time())
'Fri Sep 09 10:28:08 2016'
>>> time.asctime()
'Fri Sep 09 10:22:40 2016'
>>> time.asctime(time.localtime())
'Fri Sep 09 10:33:00 2016'
>>> time.localtime()
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=10, tm_min=1, tm_sec=19, tm_wday=4, tm_yday=253, tm_isdst=0)
>>> time.localtime(time.time())
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=10, tm_min=19, tm_sec=11, tm_wday=4, tm_yday=253, tm_isdst=0)
>>> time.gmtime()
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=2, tm_min=13, tm_sec=10, tm_wday=4, tm_yday=253, tm_isdst=0)
>>> time.gmtime(time.time())
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=2, tm_min=15, tm_sec=35, tm_wday=4, tm_yday=253, tm_isdst=0) struct_timehas nine fields; the first six are year, month, day, hour, minute, second, and the last three are:
tm_wday – day of the week (Sunday is 0).
tm_yday – day of the year.
tm_isdst – daylight‑saving flag.
Time Formatting
time.mktime() converts a struct_time into a Unix timestamp.
>> time.mktime(time.localtime())
1473388585.0time.strftime(format[, t]) formats a struct_time (or the current local time if t is omitted) into a string. If any component is out of range, a ValueError is raised.
%c – locale’s appropriate date and time representation
%x – locale’s appropriate date representation
%X – locale’s appropriate time representation
%y – year without century (00‑99)
%Y – full year
%m – month (01‑12)
%b – locale’s abbreviated month name
%B – locale’s full month name
%d – day of the month (01‑31)
%j – day of the year (001‑366)
%U – week number of the year (Sunday as first day)
%W – week number of the year (Monday as first day)
%w – weekday as a decimal number (0‑6, Sunday is 0)
%a – locale’s abbreviated weekday name
%A – locale’s full weekday name
%H – hour (24‑hour clock, 00‑23)
%I – hour (12‑hour clock, 01‑12)
%p – locale’s AM/PM indicator (effective only with %I)
%M – minute (00‑59)
%S – second (00‑61, allowing for leap seconds)
%Z – time zone name (empty string if unknown)
%% – literal ‘%’ character
>> time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
'2016-09-09 10:54:21'time.strptime(string[, format]) parses a formatted time string into a struct_time. It is essentially the inverse of strftime.
>> time.strptime(time.ctime())
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=11, tm_min=0, tm_sec=4, tm_wday=4, tm_yday=253, tm_isdst=-1)Timer Functions
time.sleep(secs) suspends the calling thread for the given number of seconds.
time.clock() has platform‑dependent semantics. On Unix it returns process time as a floating‑point number of seconds; on Windows the first call returns wall‑clock time, and subsequent calls return the elapsed time since the first call, based on QueryPerformanceCounter.
import time
time.sleep(1)
print("clock1:%s" % time.clock())
time.sleep(1)
print("clock2:%s" % time.clock())
time.sleep(1)
print("clock3:%s" % time.clock())Result (example):
clock1:1.57895443216e-06
clock2:1.00064381867
clock3:2.00158724394Other Built‑in Functions
altzone() – returns the offset in seconds of the westernmost part of the time zone during DST (negative for eastern zones).
tzset() – reinitialises time‑related settings from the environment variable TZ.
Module Attributes
timezone – offset in seconds of the local (non‑DST) time zone from GMT (positive in the Americas, non‑positive elsewhere).
tzname – a pair of strings: the first is the time‑zone name when DST is in effect, the second when it is not.
import time
print(time.timezone)
print(time.tzname)
print(time.tzname[0].decode("GBK"))
print(time.tzname[1].decode("GBK"))Result (example):
-28800
('中国标准时间', '中国夏令时')
中国标准时间
中国夏令时datetime Module
The datetime module builds on time and provides richer functionality.
Classes defined in datetime:
date – represents a calendar date (year, month, day).
time – represents a time of day (hour, minute, second, microsecond, optional tzinfo).
datetime – combines date and time.
timedelta – represents a duration between two dates or times.
tzinfo – abstract base class for time‑zone information.
All these objects are immutable.
date Class
Key class methods and attributes:
max, min – the largest and smallest representable dates.
resolution – smallest possible difference (one day).
today() – returns a date representing the current local date.
fromtimestamp(timestamp) – creates a date from a Unix timestamp.
fromordinal(ordinal) – converts a Gregorian ordinal to a date (rarely used).
from datetime import date
import time
print('date.max:', date.max)
print('date.min:', date.min)
print('date.resolution:', date.resolution)
print('date.today():', date.today())
print('date.fromtimestamp():', date.fromtimestamp(time.time()))Result (example):
date.max: 9999-12-31
date.min: 0001-01-01
date.resolution: 1 day, 0:00:00
date.today(): 2016-09-12
date.fromtimestamp(): 2016-09-12Instance methods and properties:
.year, .month, .day – return respective components.
.replace(year, month, day) – returns a new date with the supplied components.
.weekday() – Monday is 0, Sunday is 6.
.isoweekday() – Monday is 1, Sunday is 7.
.isocalendar() – returns a tuple (ISO year, ISO week number, ISO weekday).
.isoformat() – returns a string in ‘YYYY‑MM‑DD’ format.
.strftime(fmt) – custom formatting (same specifiers as time.strftime).
.toordinal() – returns the Gregorian ordinal of the date.
from datetime import date
import time
today = date.today()
print('today:', today)
print('.year:', today.year)
print('.month:', today.month)
print('.replace():', today.replace(year=2017))
print('.weekday():', today.weekday())
print('.isoweekday():', today.isoweekday())
print('.isocalendar():', today.isocalendar())
print('.isoformat():', today.isoformat())
print('.strftime():', today.strftime('%Y-%m-%d'))
print('.toordinal():', today.toordinal())Result (example):
today: 2016-09-12
.year: 2016
.month: 9
.replace(): 2017-09-12
.weekday(): 0
.isoweekday(): 1
.isocalendar(): (2016, 37, 1)
.isoformat(): 2016-09-12
.strftime(): 2016-09-12
.toordinal(): 736219time Class
Constructor:
datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]]). The class attributes are:
min – time(0, 0, 0, 0) max – time(23, 59, 59, 999999) resolution – one microsecond.
Instance attributes and methods:
.hour, .minute, .second, .microsecond
.tzinfo – time‑zone information
.replace([hour, minute, second, microsecond, tzinfo]) – returns a new time with the supplied components.
.isoformat() – returns ‘HH:MM:SS’ (or with microseconds).
.strftime(fmt) – custom formatting.
datetime Class
Constructor:
datetime.datetime(year, month, day[, hour, minute, second, microsecond, tzinfo]). Key class attributes and methods:
min, max – smallest and largest representable datetimes.
resolution – one microsecond.
today() – current local datetime (no tzinfo).
now([tz]) – current datetime; if tz is supplied, the result is tz‑aware.
utcnow() – current UTC datetime (tz‑naive).
fromtimestamp(timestamp[, tz]) – creates a datetime from a Unix timestamp; optional tz makes it tz‑aware.
utcfromtimestamp(timestamp) – creates a UTC datetime from a timestamp.
combine(date, time) – merges a date and a time into a datetime.
strptime(date_string, format) – parses a string according to format into a datetime.
from datetime import datetime
import time
print('datetime.max:', datetime.max)
print('datetime.min:', datetime.min)
print('datetime.resolution:', datetime.resolution)
print('today():', datetime.today())
print('now():', datetime.now())
print('utcnow():', datetime.utcnow())
print('fromtimestamp():', datetime.fromtimestamp(time.time()))
print('utcfromtimestamp():', datetime.utcfromtimestamp(time.time()))Result (example):
datetime.max: 9999-12-31 23:59:59.999999
datetime.min: 0001-01-01 00:00:00
datetime.resolution: 0:00:00.000001
today(): 2016-09-12 19:57:00.761000
now(): 2016-09-12 19:57:00.761000
utcnow(): 2016-09-12 11:57:00.761000
fromtimestamp(): 2016-09-12 19:57:00.761000
utcfromtimestamp(): 2016-09-12 11:57:00.761000timedelta Class
Created with
datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]). It represents a duration and can be added to or subtracted from date, time, or datetime objects.
from datetime import timedelta
print(timedelta(days=10))tzinfo Class
tzinfois an abstract base class; the standard library does not provide concrete subclasses. The most common way to obtain tzinfo objects is via the third‑party pytz module.
pytz Module
pytzprovides time‑zone handling (including DST) based on the Olson TZ database, ensuring consistent cross‑platform behavior.
Python’s datetime distinguishes between offset‑naive (no time‑zone info) and offset‑aware (contains tzinfo) objects. Only objects of the same kind can be compared or subtracted.
Example of creating simple tzinfo subclasses:
ZERO_TIME_DELTA = timedelta(0)
LOCAL_TIME_DELTA = timedelta(hours=8) # local offset
class UTC(tzinfo):
def utcoffset(self, dt):
return ZERO_TIME_DELTA
def dst(self, dt):
return ZERO_TIME_DELTA
class LocalTimezone(tzinfo):
def utcoffset(self, dt):
return LOCAL_TIME_DELTA
def dst(self, dt):
return ZERO_TIME_DELTA
def tzname(self, dt):
return '+08:00'Using pytz to list all time zones and common ones:
import pytz
print(len(pytz.all_timezones))
print(len(pytz.common_timezones))Result (example):
588
436Getting time zones for a specific country (e.g., China):
import pytz
print(pytz.country_timezones('cn'))Result:
['Asia/Shanghai', 'Asia/Urumqi']Demonstrating the two Chinese zones:
from datetime import datetime
import pytz
tz1 = pytz.timezone(pytz.country_timezones('cn')[0])
print(tz1)
print(datetime.now(tz1))
tz2 = pytz.timezone(pytz.country_timezones('cn')[1])
print(tz2)
print(datetime.now(tz2))Result (example):
Asia/Shanghai
2016-09-14 09:55:39.384000+08:00
Asia/Urumqi
2016-09-14 07:55:39.385000+06:00Time‑Zone Conversion
Local ↔ UTC conversion using pytz:
from datetime import datetime
import pytz
now = datetime.now()
print(now)
tz = pytz.timezone('Asia/Shanghai')
print(now.replace(tzinfo=tz))Result (example):
2016-09-14 10:29:20.200000
2016-09-14 10:29:20.200000+08:06Converting between zones with astimezone:
from datetime import datetime
import pytz
utc = pytz.utc
beijing = pytz.timezone('Asia/Shanghai')
japan = pytz.timezone('Asia/Tokyo')
now = datetime.now(beijing)
print('Beijing Time:', now)
print('UTC:', now.astimezone(utc))
print('Japan Time:', now.astimezone(japan))Result (example):
Beijing Time: 2016-09-14 10:19:22.671000+08:00
UTC: 2016-09-14 02:19:22.671000+00:00
Japan Time: 2016-09-14 11:19:22.671000+09:00In 1928, the Nationalist Government unified China and divided the country into five standard time zones. The shift from the Beijing local mean time to the 120°E standard added a 352‑second offset.
ISO 8601 Class
ISO 8601 defines a standard textual representation for dates and times, widely used in APIs.
>> import dateutil.parser
>>> dateutil.parser.parse('2008-09-03T20:56:35.450686Z') # RFC 3339 format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())
>>> dateutil.parser.parse('2008-09-03T20:56:35.450686') # ISO‑8601 extended
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.parse('20080903T205635.450686') # ISO‑8601 basic
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.parse('20080903') # date only
datetime.datetime(2008, 9, 3, 0, 0)Alternatively, using datetime.strptime:
datetime.datetime.strptime('2008-09-03T20:56:35.450686Z', '%Y-%m-%dT%H:%M:%S.%fZ')dateutil Module
Install with pip install python-dateutil.
parser.parse()
Parses many date‑time strings into datetime objects. Missing components default to the current date or midnight.
from dateutil import parser
print(parser.parse('8th March,2004'))
print(parser.parse('8 March,2004'))
print(parser.parse('March 8th,2004'))
print(parser.parse('March 8,2004'))
print(parser.parse('2016-09-14'))
print(parser.parse('20160914'))
print(parser.parse('2016/09/14'))
print(parser.parse('09/14/2016'))
print(parser.parse('09,14'))
print(parser.parse('12:00:00'))
print(parser.parse('Wed, Nov 12'))rrule.rrule()
Generates recurring dates according to a rule. Signature:
rrule(freq, dtstart=None, interval=1, wkst=None, count=None, until=None,
bysetpos=None, bymonth=None, bymonthday=None, byyearday=None,
byeaster=None, byweekno=None, byweekday=None, byhour=None,
byminute=None, bysecond=None, cache=False)Key parameters:
freq – frequency unit (YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY).
dtstart, until – start and end times.
wkst – week start day.
interval – interval between each recurrence.
count – number of occurrences.
byxxx – filters for specific components (e.g., byweekday=(MO, TU)).
See the official documentation for more details.
Arrow Library
Arrow offers a friendly API for creating, converting, and formatting dates and times, building on dateutil and aiming to reduce boilerplate.
UTC Time
import arrow
utc = arrow.utcnow()
print(utc)
print(utc.to('local'))Local Time
import arrow
now = arrow.now()
print(now)
print(now.to('UTC'))Parsing
import arrow
d1 = arrow.get('2012-06-05 16:20:03', 'YYYY-MM-DD HH:mm:ss')
print(d1)
d2 = arrow.get(1504384602)
print(d2)Unix Timestamp
import arrow
utc = arrow.utcnow()
print(utc)
unix_time = utc.timestamp
print(unix_time)
date = arrow.Arrow.fromtimestamp(unix_time)
print(date)Formatting
import arrow
now = arrow.now()
year = now.format('YYYY')
print('Year: {0}'.format(year))
date = now.format('YYYY-MM-DD')
print('Date: {0}'.format(date))
date_time = now.format('YYYY-MM-DD HH:mm:ss')
print('Date and time: {0}'.format(date_time))
date_time_zone = now.format('YYYY-MM-DD HH:mm:ss ZZ')
print('Date and time and zone: {0}'.format(date_time_zone))Convert to Regional Time
import arrow
utc = arrow.utcnow()
print(utc.to('US/Pacific').format('HH:mm:ss'))
print(utc.to('Europe/Bratislava').format('HH:mm:ss'))
print(utc.to('Europe/Moscow').format('HH:mm:ss'))Weekday
import arrow
d1 = arrow.get('1948-12-13')
print(d1.weekday())
print(d1.format('dddd'))Shift (Move) Time
import arrow
now = arrow.now()
print(now.shift(hours=5).time())
print(now.shift(days=5).date())
print(now.shift(years=-8).date())Daylight‑Saving Time
import arrow
now = arrow.now()
print(now.format('YYYY-MM-DD HH:mm:ss ZZ'))
print(now.dst())Human‑Friendly Output
import arrow
now = arrow.now()
print(now.shift(minutes=-15).humanize())
print(now.shift(hours=5).humanize())Arrow’s humanize() method produces expressions such as “15 minutes ago” or “in 5 hours”.
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.
