This article explains five levels of handling dates and time in Python, from basic operations to advanced concepts such as time zones and timestamps.
Abstract
The article begins by introducing the three basic classes in the datetime module: datetime, date, and time. It then provides examples of how to get current time information and construct and handle objects using these classes. The article proceeds to explain time calculations using the timedelta class, handling time zones using the pytz module, and understanding timestamps. Finally, the article covers switching between datetimes and strings using the strptime and strftime functions. The article emphasizes the importance of understanding these concepts for software development and provides examples to illustrate each concept.
Bullet points
The datetime module in Python has three basic classes: datetime, date, and time.
The datetime class handles year-month-day-hour-minute-second information, the date class handles year-month-day information, and the time class handles hour-minute-second information.
The current time or date can be obtained using class methods without instantiating a date or datetime object.
Time calculations can be performed using the timedelta class.
The pytz module can be used to handle time zones.
A timestamp is the number of seconds relative to the epoch time, which is the UTC time at 1970–01–01 00:00:00.
Switching between datetimes and timestamps is straightforward in Python using the datetime.timestamp() and datetime.utcfromtimestamp() methods.
Switching between datetimes and strings can be done using the strptime and strftime functions.
The strptime function converts a string to a datetime object, while the strftime function converts a datetime object to a string.
Understanding these concepts is important for software development and can help avoid errors when working with dates and time.
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 Calculations
Thanks for the timedelta class, calculating time is simple in Python.
Level 2: Handle Time Zones Skilfully
There is a commonly used module called pytz which makes switching between time zones easy. Since it’s not a built-in module, we should install it before using:
pip3 install pytz
Then handling time zones becomes simple:
We can print the checklist to check all names of time zones:
print(pytz.all_timezones)
Level 3: Clearly Understand Timestamps
In order to be efficient, the time in computers is actually represented by numbers. We can just define a special time which is represented by 0, and calculate other time based on it.
This is the idea of the timestamp. 🕐
The UTC time at 1970–01–01 00:00:00 is recorded as 0 and called the epoch time orUnix time. A timestamp is the number of seconds relative to the epoch time.
A timestamp before the epoch time is a negative number.
A timestamp after the epoch time is a positive number.
For example, the timestamp of 1970–01–01 01:00:00 is 3600. Because it is one hour later than the epoch time and it’s equal to 3600 seconds.
Switching between datetimes and timestamps is straightforward in Python:
As the above example shown, the datetime.timestamp() method converts a datetime to a timestamp and the datetime.utcfromtimestamp() method converts a timestamp to a datetime.
It can be seen that the timestamp has nothing to do with time zones, because once a timestamp is determined, its UTC time is determined as well.
However, a datetime is relative to time zones. When we convert a timestamp to a datetime, there are two choices:
Use datetime.utcfromtimestamp() method to convert it to a UTC time.
Use datetime.fromtimestamp() method to convert it to our local time.
For example, I am living in England and my local time is one hour later than the UTC time. As the following code shown, if I convert timestamp 0 to my local time, it will be 1970–01–01 01:00:00.
Level 4: Switch Between Datetimes and Strings Properly
Switching between datetimes and strings is a common requirement. There are two functions that can help us:
datetime.strptime(): convert a string to a datetime object
datetime.strftime(): convert a datetime object to a string