Programming Essentials Python - Predefined Functions - Date Manipulation Functions

As part of our application, we often need to deal with dates. Let us get an overview about dealing with dates in Python.

  • datetime is the main library to deal with dates.

  • datetime.datetime and datetime.date are the classes as part of datetime library that can be used to deal with dates.

  • datetime.datetime is primarily used for date with timestamp and datetime.date can be used for date without timestamp.

  • When we try to print the date it will print as below (for datetime). It is due to the implementation of string representation functions such as __str__ or __repr__.

datetime.datetime(2020, 10, 7, 21, 9, 1, 39414)
  • We need to format the date using format string to display the date the way we want. These are typically used along with functions such as strptime and strftime.

    • %Y - 4 digit year
    • %m - 2 digit month
    • %d - 2 digit day within month
  • Also, datetime library provides functions such as strptime to convert strings to date objects.

  • Other important modules to manipulate dates.

    • calendar - to get the calendar-related information for dates such as day name, month name, etc.
    • datetime.timedelta - to perform date arithmetic

Key Concepts Explanation

Importing datetime

To handle date and time in Python, we import the datetime module using the alias dt.

import datetime as dt

Getting Current Date with Timestamp

To get the current date with a timestamp, we use the now() function from the datetime module.

dt.datetime.now()

Getting Current Date Without Timestamp

To get the current date without a timestamp, we import the date class and use the today() function.

from datetime import date

date.today()

Hands-On Tasks

  1. Check the current date and time using the given code snippets.
  2. Format the current date in different ways using the strftime function.

Conclusion

In this article, we covered the basics of date manipulation in Python using the datetime module. By following the hands-on tasks, you can practice working with dates and timestamps. Remember to explore further concepts and engage with the community for continuous learning.

Watch the video tutorial here