Python - Working Code Sample for Datetime and Time Modules

Python - Working Code Sample for Datetime and Time Modules

Working Code Sample for Datetime and Time Modules in Python

The Python standard library offers robust support for handling dates, times, and time intervals through two primary modules: datetime and time. These modules provide essential functionality for dealing with real-world problems involving scheduling, logging, time measurement, delays, and more. In this document, we will explore extensive code examples for both modules, demonstrating their individual capabilities as well as their interoperability in various contexts.

Introduction to datetime and time Modules

Importing Required Modules

import datetime
import time

The datetime module includes classes like datetime, date, time, timedelta, and timezone. The time module provides low-level functions to interact with the system time, sleep, and measure durations.

Working with datetime Module

Getting Current Date and Time

from datetime import datetime

current_time = datetime.now()
print("Current date and time:", current_time)

Creating Specific datetime Object

custom_dt = datetime(2024, 12, 25, 10, 30, 45)
print("Custom datetime:", custom_dt)

Accessing Individual Components

print("Year:", custom_dt.year)
print("Month:", custom_dt.month)
print("Day:", custom_dt.day)
print("Hour:", custom_dt.hour)
print("Minute:", custom_dt.minute)
print("Second:", custom_dt.second)

Formatting datetime Objects

formatted = current_time.strftime('%Y-%m-%d %H:%M:%S')
print("Formatted datetime:", formatted)

Parsing Strings into datetime Objects

dt_str = '2025-06-27 15:45:00'
parsed_dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')
print("Parsed datetime:", parsed_dt)

Comparing datetime Objects

dt1 = datetime(2025, 6, 27)
dt2 = datetime(2025, 6, 30)

print("Is dt1 before dt2?", dt1 < dt2)

Adding/Subtracting Time with timedelta

from datetime import timedelta

now = datetime.now()
future = now + timedelta(days=10)
past = now - timedelta(days=5)

print("10 days in the future:", future)
print("5 days in the past:", past)

Calculating the Difference Between Dates

start_date = datetime(2025, 6, 1)
end_date = datetime(2025, 6, 27)
diff = end_date - start_date
print("Days difference:", diff.days)

Replacing DateTime Components

replaced = current_time.replace(hour=20, minute=0)
print("Replaced datetime:", replaced)

Weekday and ISO Calendar

print("Weekday (0=Monday):", current_time.weekday())
print("ISO Weekday (1=Monday):", current_time.isoweekday())
print("ISO Calendar:", current_time.isocalendar())

Using ISO Format

print("ISO Format:", current_time.isoformat())

Working with date Class

Creating and Accessing date

from datetime import date

today = date.today()
print("Today:", today)

specific_date = date(2023, 5, 15)
print("Specific Date:", specific_date)

Comparing Dates

print("Is today > specific_date?", today > specific_date)

Getting Min and Max date

print("Minimum date:", date.min)
print("Maximum date:", date.max)

Working with time Class

Creating a time Object

from datetime import time

t = time(14, 30, 45)
print("Time:", t)

Accessing Time Components

print("Hour:", t.hour)
print("Minute:", t.minute)
print("Second:", t.second)
print("Microsecond:", t.microsecond)

Working with time Module

Getting Current Time in Seconds Since Epoch

epoch_time = time.time()
print("Time since epoch:", epoch_time)

Converting Epoch to Local Time

local_time = time.localtime(epoch_time)
print("Local time struct:", local_time)

Formatting time with asctime

print("Readable format:", time.asctime(local_time))

Using strftime in time Module

formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', local_time)
print("Formatted:", formatted_time)

Using sleep for Delay

print("Sleeping for 2 seconds...")
time.sleep(2)
print("Awake now.")

Measuring Execution Time with perf_counter

start = time.perf_counter()
for _ in range(1000000):
    pass
end = time.perf_counter()
print("Time taken:", end - start)

Datetime and Timezone Handling

Using timezone from datetime Module

from datetime import timezone, timedelta

utc_dt = datetime.now(timezone.utc)
print("UTC Time:", utc_dt)

ist = timezone(timedelta(hours=5, minutes=30))
ist_time = utc_dt.astimezone(ist)
print("IST Time:", ist_time)

Using pytz for Timezone Handling

import pytz

utc = pytz.utc
india = pytz.timezone("Asia/Kolkata")
now_utc = datetime.now(utc)
now_india = now_utc.astimezone(india)

print("UTC Time:", now_utc)
print("India Time:", now_india)

Real World Examples

Example 1: Countdown Timer

future_event = datetime(2025, 12, 31, 23, 59, 59)
now = datetime.now()
remaining = future_event - now
print("Time left:", remaining)

Example 2: Age Calculator

dob = date(1990, 7, 1)
today = date.today()
age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
print("Age:", age)

Example 3: Log Timestamps

def log_event(message):
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(f"[{timestamp}] {message}")

log_event("Program started")
time.sleep(1)
log_event("Operation completed")

Example 4: Business Days Calculator

def business_days(start_date, end_date):
    day_count = 0
    while start_date <= end_date:
        if start_date.weekday() < 5:
            day_count += 1
        start_date += timedelta(days=1)
    return day_count

start = date(2025, 6, 1)
end = date(2025, 6, 30)
print("Business days:", business_days(start, end))

Example 5: Scheduler with Delays

def scheduler():
    print("Task will run in 5 seconds...")
    time.sleep(5)
    print("Task executed at:", datetime.now())

scheduler()

Working with UTC and Conversion

utc_now = datetime.utcnow()
print("UTC now:", utc_now)

local_dt = utc_now.replace(tzinfo=timezone.utc).astimezone()
print("Local time:", local_dt)

Creating List of Dates

start = date(2025, 1, 1)
date_list = [start + timedelta(days=i) for i in range(10)]
for d in date_list:
    print(d)

The Python datetime and time modules offer versatile tools to handle nearly every time-related programming need. From simple tasks like delays and timestamp logging to complex date arithmetic and timezone-aware datetime manipulation, these libraries cover a broad spectrum. This tutorial presented comprehensive, real-world working code examples to help you understand and apply both modules effectively in your projects.

Mastering these modules is particularly useful in domains such as data science (timestamps in data), backend development (logging and session expiration), DevOps (scheduling), and more. You can now confidently format, calculate, convert, and control time in Python applications of all sizes.

logo

Python

Beginner 5 Hours
Python - Working Code Sample for Datetime and Time Modules

Working Code Sample for Datetime and Time Modules in Python

The Python standard library offers robust support for handling dates, times, and time intervals through two primary modules: datetime and time. These modules provide essential functionality for dealing with real-world problems involving scheduling, logging, time measurement, delays, and more. In this document, we will explore extensive code examples for both modules, demonstrating their individual capabilities as well as their interoperability in various contexts.

Introduction to datetime and time Modules

Importing Required Modules

import datetime import time

The datetime module includes classes like datetime, date, time, timedelta, and timezone. The time module provides low-level functions to interact with the system time, sleep, and measure durations.

Working with datetime Module

Getting Current Date and Time

from datetime import datetime current_time = datetime.now() print("Current date and time:", current_time)

Creating Specific datetime Object

custom_dt = datetime(2024, 12, 25, 10, 30, 45) print("Custom datetime:", custom_dt)

Accessing Individual Components

print("Year:", custom_dt.year) print("Month:", custom_dt.month) print("Day:", custom_dt.day) print("Hour:", custom_dt.hour) print("Minute:", custom_dt.minute) print("Second:", custom_dt.second)

Formatting datetime Objects

formatted = current_time.strftime('%Y-%m-%d %H:%M:%S') print("Formatted datetime:", formatted)

Parsing Strings into datetime Objects

dt_str = '2025-06-27 15:45:00' parsed_dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S') print("Parsed datetime:", parsed_dt)

Comparing datetime Objects

dt1 = datetime(2025, 6, 27) dt2 = datetime(2025, 6, 30) print("Is dt1 before dt2?", dt1 < dt2)

Adding/Subtracting Time with timedelta

from datetime import timedelta now = datetime.now() future = now + timedelta(days=10) past = now - timedelta(days=5) print("10 days in the future:", future) print("5 days in the past:", past)

Calculating the Difference Between Dates

start_date = datetime(2025, 6, 1) end_date = datetime(2025, 6, 27) diff = end_date - start_date print("Days difference:", diff.days)

Replacing DateTime Components

replaced = current_time.replace(hour=20, minute=0) print("Replaced datetime:", replaced)

Weekday and ISO Calendar

print("Weekday (0=Monday):", current_time.weekday()) print("ISO Weekday (1=Monday):", current_time.isoweekday()) print("ISO Calendar:", current_time.isocalendar())

Using ISO Format

print("ISO Format:", current_time.isoformat())

Working with date Class

Creating and Accessing date

from datetime import date today = date.today() print("Today:", today) specific_date = date(2023, 5, 15) print("Specific Date:", specific_date)

Comparing Dates

print("Is today > specific_date?", today > specific_date)

Getting Min and Max date

print("Minimum date:", date.min) print("Maximum date:", date.max)

Working with time Class

Creating a time Object

from datetime import time t = time(14, 30, 45) print("Time:", t)

Accessing Time Components

print("Hour:", t.hour) print("Minute:", t.minute) print("Second:", t.second) print("Microsecond:", t.microsecond)

Working with time Module

Getting Current Time in Seconds Since Epoch

epoch_time = time.time() print("Time since epoch:", epoch_time)

Converting Epoch to Local Time

local_time = time.localtime(epoch_time) print("Local time struct:", local_time)

Formatting time with asctime

print("Readable format:", time.asctime(local_time))

Using strftime in time Module

formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', local_time) print("Formatted:", formatted_time)

Using sleep for Delay

print("Sleeping for 2 seconds...") time.sleep(2) print("Awake now.")

Measuring Execution Time with perf_counter

start = time.perf_counter() for _ in range(1000000): pass end = time.perf_counter() print("Time taken:", end - start)

Datetime and Timezone Handling

Using timezone from datetime Module

from datetime import timezone, timedelta utc_dt = datetime.now(timezone.utc) print("UTC Time:", utc_dt) ist = timezone(timedelta(hours=5, minutes=30)) ist_time = utc_dt.astimezone(ist) print("IST Time:", ist_time)

Using pytz for Timezone Handling

import pytz utc = pytz.utc india = pytz.timezone("Asia/Kolkata") now_utc = datetime.now(utc) now_india = now_utc.astimezone(india) print("UTC Time:", now_utc) print("India Time:", now_india)

Real World Examples

Example 1: Countdown Timer

future_event = datetime(2025, 12, 31, 23, 59, 59) now = datetime.now() remaining = future_event - now print("Time left:", remaining)

Example 2: Age Calculator

dob = date(1990, 7, 1) today = date.today() age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day)) print("Age:", age)

Example 3: Log Timestamps

def log_event(message): timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') print(f"[{timestamp}] {message}") log_event("Program started") time.sleep(1) log_event("Operation completed")

Example 4: Business Days Calculator

def business_days(start_date, end_date): day_count = 0 while start_date <= end_date: if start_date.weekday() < 5: day_count += 1 start_date += timedelta(days=1) return day_count start = date(2025, 6, 1) end = date(2025, 6, 30) print("Business days:", business_days(start, end))

Example 5: Scheduler with Delays

def scheduler(): print("Task will run in 5 seconds...") time.sleep(5) print("Task executed at:", datetime.now()) scheduler()

Working with UTC and Conversion

utc_now = datetime.utcnow() print("UTC now:", utc_now) local_dt = utc_now.replace(tzinfo=timezone.utc).astimezone() print("Local time:", local_dt)

Creating List of Dates

start = date(2025, 1, 1) date_list = [start + timedelta(days=i) for i in range(10)] for d in date_list: print(d)

The Python datetime and time modules offer versatile tools to handle nearly every time-related programming need. From simple tasks like delays and timestamp logging to complex date arithmetic and timezone-aware datetime manipulation, these libraries cover a broad spectrum. This tutorial presented comprehensive, real-world working code examples to help you understand and apply both modules effectively in your projects.

Mastering these modules is particularly useful in domains such as data science (timestamps in data), backend development (logging and session expiration), DevOps (scheduling), and more. You can now confidently format, calculate, convert, and control time in Python applications of all sizes.

Frequently Asked Questions for Python

Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.


Python's syntax is a lot closer to English and so it is easier to read and write, making it the simplest type of code to learn how to write and develop with. The readability of C++ code is weak in comparison and it is known as being a language that is a lot harder to get to grips with.

Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works. Performance: Java has a higher performance than Python due to its static typing and optimization by the Java Virtual Machine (JVM).

Python can be considered beginner-friendly, as it is a programming language that prioritizes readability, making it easier to understand and use. Its syntax has similarities with the English language, making it easy for novice programmers to leap into the world of development.

To start coding in Python, you need to install Python and set up your development environment. You can download Python from the official website, use Anaconda Python, or start with DataLab to get started with Python in your browser.

Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.

Python alone isn't going to get you a job unless you are extremely good at it. Not that you shouldn't learn it: it's a great skill to have since python can pretty much do anything and coding it is fast and easy. It's also a great first programming language according to lots of programmers.

The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.


Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.


6 Top Tips for Learning Python

  • Choose Your Focus. Python is a versatile language with a wide range of applications, from web development and data analysis to machine learning and artificial intelligence.
  • Practice regularly.
  • Work on real projects.
  • Join a community.
  • Don't rush.
  • Keep iterating.

The following is a step-by-step guide for beginners interested in learning Python using Windows.

  • Set up your development environment.
  • Install Python.
  • Install Visual Studio Code.
  • Install Git (optional)
  • Hello World tutorial for some Python basics.
  • Hello World tutorial for using Python with VS Code.

Best YouTube Channels to Learn Python

  • Corey Schafer.
  • sentdex.
  • Real Python.
  • Clever Programmer.
  • CS Dojo (YK)
  • Programming with Mosh.
  • Tech With Tim.
  • Traversy Media.

Python can be written on any computer or device that has a Python interpreter installed, including desktop computers, servers, tablets, and even smartphones. However, a laptop or desktop computer is often the most convenient and efficient option for coding due to its larger screen, keyboard, and mouse.

Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.

  • Google's Python Class.
  • Microsoft's Introduction to Python Course.
  • Introduction to Python Programming by Udemy.
  • Learn Python - Full Course for Beginners by freeCodeCamp.
  • Learn Python 3 From Scratch by Educative.
  • Python for Everybody by Coursera.
  • Learn Python 2 by Codecademy.

  • Understand why you're learning Python. Firstly, it's important to figure out your motivations for wanting to learn Python.
  • Get started with the Python basics.
  • Master intermediate Python concepts.
  • Learn by doing.
  • Build a portfolio of projects.
  • Keep challenging yourself.

Top 5 Python Certifications - Best of 2024
  • PCEP (Certified Entry-level Python Programmer)
  • PCAP (Certified Associate in Python Programmer)
  • PCPP1 & PCPP2 (Certified Professional in Python Programming 1 & 2)
  • Certified Expert in Python Programming (CEPP)
  • Introduction to Programming Using Python by Microsoft.

The average salary for Python Developer is β‚Ή5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from β‚Ή3,000 - β‚Ή1,20,000.

The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python website, https://www.python.org/, and may be freely distributed.

If you're looking for a lucrative and in-demand career path, you can't go wrong with Python. As one of the fastest-growing programming languages in the world, Python is an essential tool for businesses of all sizes and industries. Python is one of the most popular programming languages in the world today.

line

Copyrights © 2024 letsupdateskills All rights reserved