0
0
PythonHow-ToBeginner · 3 min read

How to Use datetime Module in Python: Syntax and Examples

Use the datetime module in Python by importing it with import datetime. You can create date, time, and datetime objects, and use methods like datetime.datetime.now() to get the current date and time.
📐

Syntax

The datetime module provides classes like date, time, and datetime to work with dates and times. You start by importing the module, then create objects or call methods.

  • datetime.date(year, month, day): Creates a date object.
  • datetime.time(hour, minute, second): Creates a time object.
  • datetime.datetime(year, month, day, hour, minute, second): Creates a datetime object.
  • datetime.datetime.now(): Gets current date and time.
python
import datetime

# Create a date object
d = datetime.date(2024, 6, 1)

# Create a time object
t = datetime.time(14, 30, 0)

# Create a datetime object
dt = datetime.datetime(2024, 6, 1, 14, 30, 0)

# Get current datetime
now = datetime.datetime.now()
💻

Example

This example shows how to get the current date and time, format it as a string, and create a specific date object.

python
import datetime

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

# Format datetime as string
formatted = now.strftime('%Y-%m-%d %H:%M:%S')

# Create a specific date
birthday = datetime.date(1990, 12, 25)

print('Current datetime:', formatted)
print('Birthday:', birthday)
Output
Current datetime: 2024-06-01 00:00:00 Birthday: 1990-12-25
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting to import the datetime module.
  • Mixing up datetime.date and datetime.datetime objects.
  • Using incorrect format codes in strftime.
  • Assuming datetime.datetime.now() returns a string instead of a datetime object.
python
import datetime

# Wrong: calling now() without module
# now = now()  # NameError

# Wrong: mixing date and datetime
# d = datetime.date(2024, 6, 1)
# print(d.hour)  # AttributeError

# Right way:
now = datetime.datetime.now()
print(now.hour)
Output
0
📊

Quick Reference

Function/ClassDescription
datetime.date(year, month, day)Create a date object
datetime.time(hour, minute, second)Create a time object
datetime.datetime(year, month, day, hour, minute, second)Create a datetime object
datetime.datetime.now()Get current date and time
datetime.datetime.strftime(format)Format datetime as string
datetime.datetime.strptime(string, format)Parse string to datetime

Key Takeaways

Import the datetime module with 'import datetime' before using it.
Use datetime.datetime.now() to get the current date and time.
Create date, time, or datetime objects with their respective constructors.
Format dates and times as strings using strftime with correct format codes.
Avoid mixing date and datetime objects to prevent attribute errors.