Learn more than the basics about the date, time, and timezone in Python

Let’s become a time master in Python

Lynn Kwong
5 min readAug 13, 2021

--

All Python developers should have some knowledge about how to deal with the date and time in Python. I assume everybody has already used time.sleep() and datetime.now() in their code. However, sometimes you might come across special cases which are beyond your knowledge and you have to turn to Google every time to find the best solution for you, which can be a time-consuming process sometimes. This article goes through some of the most frequently used tricks about the date, time, and timezone in Python in our daily work, which shall help you solve different levels of time-related issues in Python.

Picture by Igor Son on Unsplash.

Let’s start from the very basics. We can use the familiar datetime module to get the current date and/or time.

now and today are Python datetime and date objects, respectively. If you need to add type hints for the datetime and date objects, you can import the datetime and date types from the datetime module and use them for typing. As the datetime and date objects are very similar and most of the time we would use the datetime object, in the remaining part of this article we will only deal with the datetime object.

The native datetime objects are not very readable. Worse still, they cannot be converted to JSON by json.dumps and you would have a type error: TypeError: Object of type datetime is not JSON serializable. In this case, we need to convert the datetime object to a string. The easiest way to use the str function:

>>> str(now)
'2021-08-12 23:48:59.912341'

Another common way is to use the isoformat() method of the datetime object. In this way, you will get the date and time in the ISO 8601 format.

>>> now.isoformat()
'2021-08-12T23:48:59.912341'

Sometimes you may want to customize the display of the date and time. For example, you may not want to display milliseconds. For this purpose, you can use the…

--

--

Lynn Kwong

I’m a Software Developer (https://superdataminer.com) keen on sharing thoughts, tutorials, and solutions for the best practice of software development.