Handling times, dates, and numbers can seem simple, but time zones, leap years, and different formats make it a complex challenge. This guide covers the essential Python 3 modules for processing these complex data types, including datetime
for handling dates and times, and shows how to convert between different numeral systems.
Table of Contents
💻 Working with `datetime`
The datetime
module is the primary tool for date and time manipulation in Python. It provides several useful objects.
- Getting the Current Time:
from datetime import datetime now = datetime.today() print(now) # e.g., 2025-08-19 14:30:55.123456
- Time Calculations with `timedelta`: You can perform calculations by adding or subtracting
timedelta
objects.from datetime import timedelta yesterday = now - timedelta(days=1) difference = now - yesterday print(difference.days) # Output: 1
💻 Parsing and Formatting Strings
Often, you’ll need to convert a string into a datetime object, or format a datetime object into a string. The strptime
and strftime
methods are used for this.
- String to Datetime (`strptime`):
my_string = "2025-09-23 21:30:15" a_date = datetime.strptime(my_string, "%Y-%m-%d %H:%M:%S")
- Datetime to String (`strftime`):
# Format as Day-Month-Year formatted_string = a_date.strftime('%d-%m-%Y') # Output: '23-09-2025'
The format codes (like %Y
for the full year) allow you to handle virtually any date and time format.
💻 Converting Between Numeral Systems
Python has built-in functions for working with different number bases, which is useful in many areas of computing.
- To Binary, Octal, Hex: The
bin()
,oct()
, andhex()
functions convert an integer to its string representation in that base.a_number = 10 print(bin(a_number)) # Output: '0b1010' print(hex(a_number)) # Output: '0xa'
- From Other Bases to Integer: The
int()
function can take a second argument specifying the base of the input string.# Convert hexadecimal '10' to integer print(int('10', 16)) # Output: 16
—
💻 Continue Your Learning Journey
- Python Project Guide: How to Get Started with Python 3
- Python Project Guide: Using Functions in Python 3
- Python Project Guide: Build an FTP Client & Server
- Python Project Guide: Making Scripts
- Python Project Guide: NumPy & SciPy: For Science!
More Topics
- Python Project Guide: NumPy & SciPy: For Science!
- Python Project Guide: Making Scripts
- Python Project Guide: Build an FTP Client & Server
- Python Project Guide: Using Functions in Python 3
- Python Project Guide: How to Get Started with Python 3
- Coding Concepts Explained: Avoid Common Coding Mistakes
- Coding Concepts Explained: The Magic of Compilers