DateTime Basics and Current Time

2 min read ·

What is datetime Module?

The datetime module in Python is used to work with dates and time.
It allows you to:
  • Get current date and time
  • Create custom date and time
  • Format date and time
  • Perform operations on dates

datetime, date, and time Classes

The datetime module provides different classes for handling date and time.
  • date → Handles only date (year, month, day)
  • time → Handles only time (hour, minute, second)
  • datetime → Handles both date and time together

Working with date Class


Working with time Class


Working with datetime Class


Getting Current Date and Time


Accessing Individual Components


Note

datetime.now() returns local date and time of your system.


Formatting using strftime()

strftime() is used to format date and time into a readable string.

Common Format Codes

  • %d → Day
  • %m → Month
  • %Y → Year
  • %H → Hour (24-hour format)
  • %M → Minute
  • %S → Second

More Formatting Examples


Pro Tip

Use strftime() to display date and time in user-friendly formats like reports, logs, and dashboards.


Exercise

  • Print current date
  • Print only time
  • Format date as DD-MM-YYYY
  • Print current day name