Python datetime

1. Overview of the datetime Module

The datetime module is used for handling date and time operations with high precision and reliability.

import datetime

print(datetime.datetime.now())

It supports full timestamping, scheduling, comparisons, and formatting.


2. Current Date and Time

from datetime import datetime

now = datetime.now()
print(now)

Returns the current system date and time including microseconds.


3. Extracting Date Components

from datetime import datetime

now = datetime.now()

print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)

Allows granular access to individual components.


4. Using date and time Objects

Separates pure date and pure time values.


5. Formatting with strftime()

Frequently used format directives:

  • %d → Day

  • %B → Full month name

  • %A → Weekday name


6. Parsing Strings with strptime()

Transforms formatted strings into datetime objects.


7. Time Difference using timedelta

Controls duration logic precisely.


8. Timezone Handling with zoneinfo

Critical for international systems and APIs.


9. ISO Format Conversion

Produces standardized time format (ISO 8601) for interoperability.


10. Practical Example: Scheduling Logic

Used in reminders, CRON systems, task automation, and expiry tracking.


Common Errors with datetime

Issue
Cause

TypeError

Mixing strings and datetime objects

ValueError

Incorrect parsing format

Timezone mismatch

Naive vs aware datetime


Enterprise Use-Cases

  • Token expiration validation

  • Log timestamping

  • Activity scheduling

  • Time-based reporting

  • SLA monitoring


Last updated