5 Levels of Handling Date and Time in Python

Yang Zhou
TechToFreedom
Published in
3 min readDec 3, 2020

--

5 Levels of Handling Date and Time in Python
Photo by shota James on Unsplash

Handling dates and time is a common requirement for software developments. However, since dates and time are special data types, it’s could be confusing and error-prone for some operations, such as switching between different date formats or time zones.

Believe it or not, many programmers, no matter how many years they have been working, keep encountering problems about dates or time operations. This is why this article is a must-read one.

This article will explain 5 important operations of dates and time from easy to hard. After reading, handling dates and time in Python will be just a piece of cake for you. 🍰

Level 0: Know the Basic 3 Objects in Datetime Module

All time relative objects in Python can be constructed by three basic classes of the datetime module. They are as follows:

  • datetime: An object for handling year-month-day-hour-minute-second information
  • date: An object for handling year-month-day information
  • time: An object for handling hour-minute-second information

Let’s see how to use them through concise examples:

Get current time information

We can get the current time or the date of today by class methods without instantiating a date or datetime object.

Construct and handle an object

We can construct instances of the three classes and use them according to specific needs. The following example demonstrates how to use a date object. The usages of time and datetime objects are similar.

Level 1: Be Familiar with Time…

--

--