Datetime Filehandling Exception
Datetime Filehandling Exception
• The datetime module in Python provides classes for manipulating dates and times.
• The datetime module provides several classes, including:
• datetime: Represents a date and time.
• date: Represents a date (year, month, day).
• time: Represents a time (hour, minute, second, microsecond).
datetime Class Methods
• datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0): Creates a datetime object.
Example:
from datetime import datetime
dt = datetime(2024, 4, 16, 10, 30, 0)
print(dt) # Output: 2024-04-16 10:30:00
• date(year, month, day): Creates a date object.
Example:
from datetime import date
d = date(2024, 4, 16)
print(d) # Output: 2024-04-16
time Class Methods
• time(hour=0, minute=0, second=0, microsecond=0): Creates a time object.
Example:
from datetime import time
t = time(10, 30)
print(t) # Output: 10:30:00
• today(): Returns the current local date.
Example:
from datetime import datetime
today = datetime.today()
print(today) # Output: Current date and time
• now(): Returns the current local date and time.
• strftime(format): Returns a string representing the date/time according to the format string.
• strptime(date_string, format): Parses a string representing a date/time into a datetime object.
timedelta Class
• timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0): Represents a
duration.
Example
from datetime import datetime, timedelta
today = datetime.today()
future_date = today + timedelta(days=7)
print(future_date) # Output: Date 7 days from now
Exception Handling
• Exception handling in Python allows you to gracefully manage errors that occur during program execution.
try-except Block
Example
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Cannot divide by zero")
Multiple Except Blocks
try:
file = open("nonexistent_file.txt", "r")
except FileNotFoundError:
print("Error: File not found")
except IOError:
print("Error: Input/output error")
Handling Multiple Exceptions
try:
age = int(input("Enter your age: "))
except (ValueError, TypeError):
print("Error: Invalid input")
else Block
try:
result = 10 / 2
except ZeroDivisionError:
print("Error: Cannot divide by zero")
else:
print("Result:", result)
finally Block
try:
file = open("data.txt", "r")
# Process the file
except IOError:
print("Error: Input/output error")
finally:
file.close()
Custom Exceptions
class NegativeNumberError(Exception):
def __init__(self, number):
self.number = number
self.message = "Error: Negative number not allowed"
def check_positive(number):
if number < 0:
raise NegativeNumberError(number)
• Raising Exceptions
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
Built-in Exceptions
1.SyntaxError: Raised when the Python parser encounters a syntax error.
# Example of SyntaxError
print("Hello, world!)
# Example of IndentationError
def my_function():
print("Indented statement")
# Example of NameError
print(my_variable)
# NameError: name 'my_variable' is not defined
# Example of TypeError
result = 10 / '2'
5.ValueError: Raised when a built-in operation or function receives an argument that has the right type but an
inappropriate value.
# Example of ValueError
num = int('abc')
# ValueError: invalid literal for int() with base 10: 'abc'
6.ZeroDivisionError: Raised when division or modulo by zero is performed.
# Example of ZeroDivisionError
result = 10 / 0
# ZeroDivisionError: division by zero
Opening a File
file = open(filename, mode)
filename: Name of the file to be opened.
mode: Specifies the mode in which the file is opened ('r' for reading, 'w' for writing, 'a' for appending, etc.).
Example:
file = open("example.txt", "r")
Reading from a File: Reads the entire contents of the file as a string.
content = file.read()
Example:
with open("example.txt", "r") as file:
content = file.read()
print(content)
Writing to a File: Writes the specified content to the file.
file.write(content)
Example:
with open("output.txt", "w") as file:
file.write("Hello, world!")
Appending to a File: Opens the file in append mode and adds the specified content to the end of the file.
file = open(filename, "a")
file.write(content)
Example:
with open("output.txt", "a") as file:
file.write("\nAppending additional content.")
Closing a File: Closes the file, releasing any system resources associated with it.
file.close()
Example:
file = open("example.txt", "r")
content = file.read()
file.close()
Using with Statement: Automatically closes the file when the block is exited, ensuring proper resource
management.
with open(filename, mode) as file:
# Perform file operations:
Example:
with open("example.txt", "r") as file:
content = file.read()
File Modes:
'r': Read mode (default). Opens the file for reading.
'w': Write mode. Opens the file for writing. If the file exists, it will be overwritten. If the file does not exist, a
new file will be created.
'a': Append mode. Opens the file for appending. New data will be written to the end of the file.
Example:
with open("example.txt", "w") as file:
file.write("Content written in write mode.")