Skip to content

python datetime module

Ray edited this page Jul 4, 2025 · 6 revisions

The datetime module offers several classes to work with dates and times:

date class:

Represents a date (year, month, day).

  • date.today(): Returns the current local date.
  • date(year, month, day): Creates a date object for a specific date.

time class:

Represents a time (hour, minute, second, microsecond).

datetime class:

Represents a combination of date and time.

  • datetime.now(): Returns the current local date and time.
  • datetime(year, month, day, hour, minute, second, microsecond): Creates a datetime object for a specific date and time.
  • timedelta class: Represents a duration or difference between two date, time, or datetime objects. Example Usage:
from datetime import date, datetime, timedelta

# Get the current date
today = date.today()
print(f"Today's date: {today}")

# Get the current date and time
now = datetime.now()
print(f"Current date and time: {now}")

# Create a specific date
specific_date = date(2025, 7, 4)
print(f"Specific date: {specific_date}")

# Add a duration to a date
future_date = today + timedelta(days=10)
print(f"Date in 10 days: {future_date}")

# Format a date/datetime object into a string
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted date and time: {formatted_date}")

Clone this wiki locally