Python Project Guide: Times, Dates & Numbers

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.

💻 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(), and hex() 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

More Topics

Hello! I'm a gaming enthusiast, a history buff, a cinema lover, connected to the news, and I enjoy exploring different lifestyles. I'm Yaman Şener/trioner.com, a web content creator who brings all these interests together to offer readers in-depth analyses, informative content, and inspiring perspectives. I'm here to accompany you through the vast spectrum of the digital world.

Leave a Reply

Your email address will not be published. Required fields are marked *