Python Date and Time Modules Guide
1. time Module Overview
The time module provides functions to work with time-related tasks. It includes low-level system functions like
delays, timestamps, and formatting. The most used functions are:
- time.time(): Returns the current time in seconds since the epoch (1970).
- time.sleep(seconds): Delays execution.
- time.localtime(): Converts seconds to struct_time object.
- time.strftime(format, struct_time): Formats a struct_time object to string.
Note: If you omit the second argument in time.strftime(), it defaults to time.localtime().
2. datetime Module Overview
The datetime module provides classes for manipulating dates and times in a more object-oriented way. Key
classes include:
- datetime: Includes both date and time.
- date: Only the date part.
- time: Only the time part.
- timedelta: Represents a duration.
Usage:
from datetime import datetime
now = datetime.now()
formatted = now.strftime('%Y-%m-%d %H:%M:%S')
3. strftime/strptime Format Codes Table
%Y: Full year (2025)
%y: Year (25)
%m: Month (07)
Python Date and Time Modules Guide
%B: Full month name (July)
%b: Abbreviated month name (Jul)
%d: Day (12)
%A: Full weekday name (Saturday)
%a: Abbreviated weekday name (Sat)
%H: Hour (24-hour, 14)
%I: Hour (12-hour, 02)
%p: AM/PM (PM)
%M: Minute (30)
%S: Second (08)
%f: Microseconds (548513)
%z: UTC offset (+0530)
%Z: Timezone (IST)
%j: Day of year (193)
%U: Week number (Sun-start, 27)
%W: Week number (Mon-start, 27)
%c: Locale date+time
%x: Locale date
%X: Locale time
%%: Literal percent
4. time.strftime() vs datetime.strftime()
time.strftime() is a standalone function and can optionally take a struct_time object. If no object is provided, it
defaults to time.localtime().
datetime.strftime() is an instance method and must be called on a datetime object. It cannot take an external
object.
Example (time module):
import time
Python Date and Time Modules Guide
print(time.strftime('%c')) # Works
print(time.strftime('%c', time.localtime())) # Also works
Example (datetime module):
from datetime import datetime
now = datetime.now()
print(now.strftime('%c')) # Correct
# datetime.strftime('%c') # Error: must call on an object
5. Summary Table
| Feature | time.strftime() | datetime.strftime() |
|---------------------------|----------------------------------|--------------------------------------|
| Type | Standalone function | Instance method |
| Called On | Module | datetime object |
| Accepts external object? | Yes (struct_time) | No |
| Object required? | No (defaults to localtime) | Yes |