Python DateTime, TimeDelta, Strftime(Format) with Examples

Created with Sketch.

 
 

In Python, the datetime module provides classes for working with dates and times. Here’s a brief overview of datetime, timedelta, and strftime with examples:

1. datetime:

The datetime class is used to represent dates and times. Here’s how you can create a datetime object:

from datetime import datetime

# Get the current date and time
current_datetime = datetime.now()

print(f"Current Date and Time: {current_datetime}")

2. timedelta:

The timedelta class represents the duration between two dates or times. It can be used for arithmetic operations on dates. Here’s an example:

from datetime import datetime, timedelta

# Get the current date and time
current_datetime = datetime.now()

# Create a timedelta of 5 days
delta = timedelta(days=5)

# Calculate a new date by adding the timedelta
new_datetime = current_datetime + delta

print(f"Current Date and Time: {current_datetime}")
print(f"New Date and Time (+5 days): {new_datetime}")

3. strftime (String Formatting Time):

The strftime method is used to format datetime objects as strings according to a specified format. Here’s an example:

from datetime import datetime

# Get the current date and time
current_datetime = datetime.now()

# Format the datetime as a string
formatted_string = current_datetime.strftime("%Y-%m-%d %H:%M:%S")

print(f"Formatted String: {formatted_string}")

In the example above, %Y, %m, %d, %H, %M, and %S are format codes representing year, month, day, hour, minute, and second, respectively.

These are basic examples, and there are many more options for formatting dates and times using strftime. You can refer to the official Python documentation for the full list of format codes: strftime() and strptime() Format Codes.

Leave a Reply

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