Advanced DateTime

2 min read ·

A timezone represents a specific region’s local time.
By default, datetime.now() gives local time without timezone information (called naive datetime).
To work with timezones, Python provides timezone-aware datetime objects.

Note

Datetime objects without timezone are called naive, and with timezone are called aware.


UTC vs Local Time

  • UTC (Coordinated Universal Time) → Standard global time
  • Local time → Time based on your system or region

Converting UTC to Local Time


Pro Tip

Always store time in UTC and convert to local time when displaying to users.


datetime vs time Module Difference

  • datetime module → Full date and time handling
  • time module → Low-level time operations (timestamps, delays)

Real-world Use Cases

Logging Example


Scheduling Example


Real World Scenario

Applications like booking systems, payment systems, and notifications rely heavily on accurate date and time handling.


Best Practices

  • Use UTC for storing time
  • Use timezone-aware datetime when needed
  • Format datetime properly for display
  • Avoid mixing naive and aware datetime objects

Common Mistakes

Stop
  • Ignoring timezones in global applications
  • Using wrong format in strptime
  • Mixing datetime and string without conversion
  • Assuming local time is same everywhere