Python's `datetime` module provides classes for working with dates and times. It's a powerful tool for any application that deals with time-sensitive data.
Getting the Current Date and Time
from datetime import datetime, date
# Get the current date and time
now = datetime.now()
print(f"Current datetime: {now}")
# Get the current date only
today = date.today()
print(f"Current date: {today}")
Formatting Dates with `strftime`
The `strftime()` method formats a datetime object into a string based on specific format codes.
from datetime import datetime
now = datetime.now()
# Format codes:
# %Y - Year with century (e.g., 2025)
# %m - Month as a zero-padded decimal number (01-12)
# %d - Day of the month as a zero-padded decimal number (01-31)
# %H - Hour (24-hour clock) (00-23)
# %M - Minute (00-59)
# %S - Second (00-61)
formatted_string = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted: {formatted_string}")
Parsing Strings into Dates with `strptime`
The `strptime()` method parses a string representing a date and time and converts it into a datetime object.
from datetime import datetime
date_string = "2025-12-25 14:30:00"
datetime_object = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"Parsed object: {datetime_object}")
print(f"Year: {datetime_object.year}")
Comments
Post a Comment