Fundamentals 24 min read

Advanced Number, Date, and Formatting Techniques in Python

This article explains how to perform precise numeric operations, format numbers, convert between bases, handle complex numbers, work with infinities and NaN, use fractions, manipulate large arrays with NumPy, generate random data, and manage dates, times, and time zones in Python.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Advanced Number, Date, and Formatting Techniques in Python

Python provides built‑in functions and modules for precise numeric operations, including rounding with round() , decimal arithmetic via the decimal module, and flexible formatting with format() and f‑strings.

<code>>> round(1.23, 1)
1.2
>>> from decimal import Decimal
>>> Decimal('1.23') + Decimal('2.34')
Decimal('3.57')
>>> format(1234.567, '0.2f')
'1234.57'
</code>

Binary, octal, and hexadecimal representations can be obtained with bin() , oct() , and hex() , or with format() for custom output without prefixes.

<code>>> bin(1234)
'0b10011010010'
>>> format(1234, 'b')
'10011010010'
>>> format(1234, 'x')
'4d2'
</code>

Large integers can be packed into or unpacked from byte strings using int.to_bytes() and int.from_bytes() , which is useful for binary protocols or IP address handling.

<code>>> x = 94522842520747284487117727783387188
>>> x.to_bytes(16, 'big')
 b'\x00\x124V\x00x\x90\xab\x00\xcd\xef\x01\x00#\x004'
>>> int.from_bytes(b'\x00\x124V\x00x\x90\xab\x00\xcd\xef\x01\x00#\x004', 'big')
94522842520747284487117727783387188
</code>

Complex numbers are supported via the complex() constructor or the j suffix, with access to real, imaginary, and magnitude via attributes and the cmath module for advanced functions.

<code>>> a = complex(2, 4)
>>> a.real
2.0
>>> a.imag
4.0
>>> import cmath
>>> cmath.sqrt(a)
(1.4142135623730951+1.414213562373095j)
</code>

Python can represent positive/negative infinity and NaN using float('inf') , float('-inf') , and float('nan') . The math module offers isinf() and isnan() for testing, and arithmetic with these values follows IEEE‑754 rules.

<code>>> a = float('inf')
>>> a + 5
inf
>>> math.isnan(float('nan'))
True
</code>

The fractions module enables exact rational arithmetic, with methods such as limit_denominator() and conversion to float when needed.

<code>>> from fractions import Fraction
>>> a = Fraction(5, 4)
>>> b = Fraction(7, 16)
>>> a + b
Fraction(27, 16)
>>> a.limit_denominator(8)
Fraction(4, 3)
</code>

For large‑scale numeric computation, NumPy supplies n‑dimensional arrays, vectorized operations, and linear‑algebra utilities, offering performance comparable to compiled languages.

<code>>> import numpy as np
>>> arr = np.array([1, 2, 3, 4])
>>> arr * 2
array([2, 4, 6, 8])
>>> np.linalg.det(np.matrix([[1, -2, 3],[0,4,5],[7,8,-9]]))
-229.99999999999983
</code>

The random module provides functions for random selection, shuffling, integer generation, and sampling from various distributions, while cryptographic‑secure randomness should be obtained from ssl.RAND_bytes() or secrets .

<code>>> import random
>>> random.choice([1,2,3,4])
2
>>> random.sample([1,2,3,4,5,6], 3)
[4, 1, 5]
</code>

Date and time handling is performed with the datetime module, using timedelta for arithmetic, strftime/strptime for parsing/formatting, and the calendar module for month ranges. For timezone‑aware calculations, the pytz library (or the built‑in zoneinfo in newer Python) localises naive datetimes and converts between zones.

<code>>> from datetime import datetime, timedelta, timezone
>>> utc_now = datetime.utcnow().replace(tzinfo=timezone.utc)
>>> beijing = utc_now.astimezone(timezone(timedelta(hours=8), name='Asia/Shanghai'))
>>> beijing.strftime('%Y-%m-%d %H:%M:%S')
'2022-05-04 19:11:45'
</code>

Together, these tools allow developers to handle numeric precision, base conversions, large integers, complex arithmetic, random data generation, and robust date‑time manipulation in Python applications.

DateTimeNumPyDecimalRandomNumber FormattingComplex Numbers
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.