Working with Datetime and Timedelta in Python

This week’s assignment focused on using the datetime and timedelta modules in Python. I practiced working with time-based objects, performing calculations, and combining date/time data with custom functions.

Code Procedure:
  1. Simulated reading transaction data and displayed the item/cost with the current time using datetime.now()

  2. Used timedelta to subtract 60 seconds and add 2 years (730 days) to the current time.

  3. Created a timedelta object representing 100 days, 10 hours, and 13 minutes and printed the result.

  4. Wrote a function that takes 2 arguments (feet and inches) and prints them along with the current datetime.

These exercises helped me better understand how Python handles time-based data and how to apply that to real-world scenarios.

Code:

from datetime import datetime, timedelta


# 1. Display current time with item & cost

sample_data = "2025-06-29\t11:23:00\tPublix\tMilk\t3.25\tCredit"

data = sample_data.strip().split("\t")

if len(data) == 6:

    _, _, _, item, cost, _ = data

    print("Current time:", datetime.now())

    print(f"Item: {item}\tCost: {cost}")


# 2. Add 2 years and subtract 60 seconds

now = datetime.now()

future = now + timedelta(days=730) - timedelta(seconds=60)

print("Modified time:", future)


# 3. Create specific timedelta

d = timedelta(days=100, hours=10, minutes=13)

print("Timedelta:", d)


# 4. Function with 2 arguments + datetime

def print_height_with_time(feet, inches):

    print(f"Height: {feet} ft, {inches} in — Time: {datetime.now()}")


print_height_with_time(6, 1)


Output:

Current time: 2025-06-30 03:37:00.777149
Item: Milk Cost: 3.25
Modified time: 2027-06-30 03:36:00.777191
Timedelta: 100 days, 10:13:00
Height: 6 ft, 1 in — Time: 2025-06-30 03:37:00.777230

Comments

Popular posts from this blog

Module 8: PHP Forms and GET vs POST

Module 2: Introduction to HTML, CSS, and FTP