Skip to content

Python datetime Module

Python’s datetime module is a standard library module for handling dates and times. It provides multiple classes and functions to help us easily handle date, time, and time difference operations. Whether it’s getting the current time, formatting dates, or calculating time differences, the datetime module can handle it all.

The datetime module includes the following core classes:

  • date class - The date class represents a date, containing year, month, and day attributes.

  • time class - The time class represents a time, containing hour, minute, second, microsecond, and other attributes.

  • datetime class - The datetime class is a combination of date and time, allowing simultaneous representation of both date and time.

  • timedelta class - The timedelta class represents a time difference and can be used for addition and subtraction operations on dates and times.


We can use the now() method of the datetime class to get the current date and time.

from datetime import datetime

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

Output example:

Current time: 2025-04-22 14:30:45.123456

We can create a specific date and time using the constructor of the datetime class.

from datetime import datetime

# Create a specific date and time
specific_time = datetime(2025, 4, 22, 15, 30, 0)
print("Specific time:", specific_time)

Output example:

Specific time: 2025-04-22 15:30:00

datetime objects can be formatted as strings using the strftime() method.

from datetime import datetime

# Get the current time
now = datetime.now()

# Format output
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted time:", formatted_time)

Output example:

Formatted time: 2025-04-22 14:30:45

The timedelta class can be used to calculate the difference between two dates or times.

from datetime import datetime, timedelta

# Get the current time
now = datetime.now()

# Calculate the time 10 days later
future_time = now + timedelta(days=10)
print("Time after 10 days:", future_time)

Output example:

Time after 10 days: 2025-05-02 14:30:45.123456

Calculating the Number of Days Between Two Dates

Section titled “Calculating the Number of Days Between Two Dates”
from datetime import date

# Create two dates
date1 = date(2025, 4, 22)
date2 = date(2025, 5, 1)

# Calculate the day difference
delta = date2 - date1
print("Day difference between the two dates:", delta.days)

Output example:

Day difference between the two dates: 9

The datetime module itself does not directly support time zone operations, but the pytz library can be used to handle time zones.

from datetime import datetime
import pytz

# Get the current time and set the time zone
now = datetime.now(pytz.timezone('Asia/Shanghai'))
print("Current time in Shanghai:", now)

Output example:

Current time in Shanghai: 2025-04-22 14:30:45.123456+08:00

Class Description Example
datetime.date Date class (year, month, day) date(2023, 5, 15)
datetime.time Time class (hour, minute, second, microsecond) time(14, 30, 0)
datetime.datetime Datetime class (includes both date and time) datetime(2023, 5, 15, 14, 30)
datetime.timedelta Time interval class (for date/time calculations) timedelta(days=5)
datetime.tzinfo Time zone information base class (requires subclassing) Custom time zone class

2. Common Methods/Attributes of the date Object

Section titled “2. Common Methods/Attributes of the date Object”
Method/Attribute Description Example
date.today() Returns the current local date date.today()date(2023, 5, 15)
date.fromisoformat(str) Parses a date from a YYYY-MM-DD string date.fromisoformat("2023-05-15")
date.year Year (read-only) d.year2023
date.month Month (1-12, read-only) d.month5
date.day Day (1-31, read-only) d.day15
date.weekday() Returns day of the week (0=Monday, 6=Sunday) d.weekday()0
date.isoformat() Returns a YYYY-MM-DD format string d.isoformat()"2023-05-15"
date.strftime(format) Custom formatted output d.strftime("%Y/%m/%d")"2023/05/15"

3. Common Methods/Attributes of the time Object

Section titled “3. Common Methods/Attributes of the time Object”
Method/Attribute Description Example
time.hour Hour (0-23, read-only) t.hour14
time.minute Minute (0-59, read-only) t.minute30
time.second Second (0-59, read-only) t.second0
time.microsecond Microsecond (0-999999, read-only) t.microsecond0
time.isoformat() Returns a HH:MM:SS.mmmmmm format string t.isoformat()"14:30:00"
time.strftime(format) Custom formatted output t.strftime("%H:%M")"14:30"

4. Common Methods/Attributes of the datetime Object

Section titled “4. Common Methods/Attributes of the datetime Object”
Method/Attribute Description Example
datetime.now() Returns the current local datetime datetime.now()datetime(2023, 5, 15, 14, 30, 0)
datetime.utcnow() Returns the current UTC datetime datetime.utcnow()
datetime.fromtimestamp(ts) Creates a datetime object from a timestamp datetime.fromtimestamp(1684146600)
datetime.timestamp() Returns the timestamp (floating-point seconds) dt.timestamp()1684146600.0
datetime.date() Extracts the date part dt.date()date(2023, 5, 15)
datetime.time() Extracts the time part dt.time()time(14, 30)
datetime.year Year (same as date) dt.year2023
datetime.strftime(format) Custom formatted output dt.strftime("%Y-%m-%d %H:%M")"2023-05-15 14:30"

5. Common Attributes of the timedelta Object

Section titled “5. Common Attributes of the timedelta Object”
Attribute Description Example
days Days (can be positive or negative) delta.days5
seconds Seconds (0-86399) delta.seconds3600 (1 hour)
microseconds Microseconds (0-999999) delta.microseconds0
Symbol Description Example Output
%Y Four-digit year 2023
%m Two-digit month (01-12) 05
%d Two-digit day (01-31) 15
%H 24-hour hour (00-23) 14
%M Minute (00-59) 30
%S Second (00-59) 00
%A Full weekday name Monday
%a Abbreviated weekday name Mon
%B Full month name May
%b Abbreviated month name May

1. Calculating Date Difference

from datetime import date, timedelta

d1 = date(2023, 5, 15)
d2 = date(2023, 6, 1)
delta = d2 - d1  # Returns a timedelta object
print(delta.days)  # Output: 17

2. Time Addition and Subtraction

from datetime import datetime, timedelta

now = datetime.now()
future = now + timedelta(days=3, hours=2)
print(future.strftime("%Y-%m-%d %H:%M"))
from datetime import datetime
import pytz

utc_time = datetime.utcnow().replace(tzinfo=pytz.utc)
beijing_time = utc_time.astimezone(pytz.timezone("Asia/Shanghai"))
print(beijing_time)

4. Parsing Strings

from datetime import datetime

dt = datetime.strptime("2023-05-15 14:30", "%Y-%m-%d %H:%M")
print(dt.year)  # Output: 2023
  1. Immutability: All datetime objects are immutable; operations return new objects.

  2. Time Zone Handling: Native datetime has no time zone support; use pytz or Python 3.9+’s zoneinfo.

  3. Performance: Frequent object creation may affect performance; consider reuse or caching.

  4. Boundary Checks: Illegal dates (e.g., date(2023, 2, 30)) will trigger a ValueError.