Python datetime Module

Introduction

Welcome to our comprehensive guide on Python’s datetime module! In the world of programming, handling dates and times is a common requirement.

Features

The datetime module in Python boasts a range of features that make it an indispensable tool for working with date and time data:

  • Precise date and time representation.
  • Time zone awareness for handling time differences.
  • Arithmetic operations on dates and times.
  • Formatting and parsing of date and time strings.
  • Support for both Gregorian and Julian calendar systems.
  1. datetime.now() – Current Date and Time:

Returns the current date and time.

         2. datetime.combine() – Combine Date and Time:

Combines a date and a time into a single datetime object.

        3. datetime.strptime() – String to Datetime:

Converts a string to a datetime object based on a specified format.

Common Format Codes

CodeMeaning
%YYear (2025)
%yYear (25)
%mMonth (01-12)
%BMonth (full name)
%dDay (01-31)
%AWeekday (full name)
%HHour (24 hr)
%IHour (12 hr)
%MMinute
%SSecond

        4. datetime.strftime() – Datetime to String:

Formats a datetime object as a string according to a given format.

        5. timedelta() – Time Interval:

Represents a duration of time, supporting arithmetic operations with datetime objects.

        6. datetime.date() – Extract Date:

Extracts the date portion from a datetime object.

        7. datetime.time() – Extract Time:

Extracts the time portion from a datetime object.

        8. datetime.replace() – Replace Components:

Creates a new datetime object by replacing specific components.

        9. datetime.weekday() – Weekday Index:

Returns the index of the weekday (0 for Monday, 6 for Sunday).

       10. datetime.isoweekday() – ISO Weekday:

Returns the ISO weekday (1 for Monday, 7 for Sunday).

       11. datetime.timestamp() – Unix Timestamp:

Returns the Unix timestamp (the number of seconds since January 1, 1970).

       12. datetime.astimezone() – Timezone Conversion:

Converts a datetime object to a different timezone.

       13. datetime.utcoffset() – UTC Offset:

Returns the UTC offset of a datetime object.

       14. datetime.timedelta.total_seconds() – Total Seconds:

Returns the total number of seconds in a timedelta object.

       15. datetime.fromtimestamp() – Datetime from Timestamp:

Creates a datetime object from a Unix timestamp.

Leave a Comment