The datetime module from the standard Python programming language library is a collection of a variety of classes for convenient work with time and dates. With many built-in methods for convenient display as well as manipulation of time and dates, it increases the functionality of some programs.
The datetime library is used to work with time and dates in Python, allowing to present this information in the most convenient form. It consists of several classes. With these classes, the programmer has access to many useful methods:
- Getting the current system date and time;
- Calculating the difference between dates and other arithmetic operations;
- Operations that allow you to compare times;
- Formatted output of date and time information.
The module uses the MINYEAR and MAXYEAR constants, which are 1 and 9999 respectively. This is the minimum and maximum possible value of the year used in the library.
The difference between datetime and time
But in Python, besides the datetime library, there is also the time library. Let’s figure out which one we should use: The time module is usually used when working with the current time, based on the value in seconds since the epoch began. It allows you to make its formatted output. There are options to set pauses in script execution using the sleep method. Used to calculate the running time of a program using monotonic. Unlike the time module, datetime has several built-in classes that allow you to perform various manipulations with date and time, such as arithmetic operations or comparison.
The datetime module includes several different classes, each with their own methods and properties, as well as serving specific purposes. All of them are presented in the following table with their names and brief characteristics.
|date||represents the date, completely excluding the time data, based on the Gregorian calendar|
|time||includes the time data, ignoring the date data completely|
|datetime||contains the time and date information, based on the Gregorian calendar|
|timedelta||describes a specific period of time that lies between two different moments|
|tzinfo||presents different information about the time zone|
|timezone||describes the time, referring to the UTC standard|
In the following, we will look at how you can use these classes in Python to work with date and time. Let’s look at some basic examples of using the datetime library.
The date class is used to represent date data, which includes year, month, and number. To be able to use this class, you must first import the datetime module by placing the corresponding instruction at the beginning of the program code file. To create objects of datetime type, call the constructor of the same name, specifying the datetime information as parameters. In this case, do not forget about the order of the arguments: year, then month and date. The following example shows the creation of a date object, where the variable a receives the three above values. After that, the date is printed using the print method and the type function gives the class name of the object.
import datetime a = datetime.date(2001, 10, 28) print(a) print(type(a)) 2001-10-28 <class 'datetime.date'>
If you need to get information about the current date in Python, you do not need to call the standard date constructor and manually type in the appropriate values. The built-in today method does the job just fine. The following snippet of code shows how to quickly assign the current date to an object and then print out this information.
import datetime a = datetime.date.today() print(a) 2018-11-08
Sometimes you have to work not only with the general date information, but also with its individual components, year, month, or day. You can access these object properties using the point operator. Remember, however, that they cannot be changed from the current object. The following example shows how the a variable is initialized with the constructor, after which all its properties are displayed separately.
import datetime a = datetime.date(2012, 7, 21) print(a.year) print(a.month) print(a.day) 2012 7 21
The class time serves to show time data, ignoring date completely. As with the previous date class, you must import the datetime module with the import keyword. You can create an object belonging to the type time using the constructor, which accepts arguments such as the number of hours, minutes, seconds, and microseconds. When specifying these parameters, you should not forget about their necessary order, placing the numbers in the correct positions. You should also remember that there are restrictions, for example, you cannot display the time with a value greater than 59 in place of seconds. The following code snippet creates a variable a, to which an object of type time is assigned with four different properties: the number of hours, minutes, seconds and microseconds. The print method prints information about this object, while the type function displays its class.
import datetime a = datetime.time(12, 18, 35, 5867) print(a) print(type(a)) 12:18:35.005867 <class 'datetime.time'>
You don’t need to specify all of its properties in the constructor to create an object of type time. As you can see from the results of the program below, missing time data is automatically filled with zeros, while the numbers entered are added to the object from larger to smaller numbers. This initializes the three different variables a, b and c and then print methods print the information about their current state to the display.
import datetime a = datetime.time(23, 5, 30) b = datetime.time(7, 26) c = datetime.time(21) print(a) print(b) print(c) 23:05:30 07:26:00 21:00:00
Just as with the date class, you can also use time to access the individual values of a previously created object: hours, minutes, seconds, and microseconds. To do so, apply the point operator, and then specify a specific property. The following example shows the output of information that represents the individual details of object a.
import datetime a = datetime.time(16, 3, 49, 23578) print(a.hour) print(a.minute) print(a.second) print(a.microsecond) 16 3 49 23578
The datetime class allows you to describe data about a particular moment in time, which takes into account not only the hours and minutes, but also the information about the date. As with the previous object types, a constructor is used here with several arguments under each value. The following example demonstrates a program where a variable named a gets an object from the standard datetime constructor, then outputs its value and type.
import datetime c = datetime.datetime(2017, 7, 18, 4, 52, 33, 51204) print(c) print(type(c)) 2017-07-18 04:52:33.051204 <class 'datetime.datetime'>
You can create objects with a different set of parameters, specifying only the required information. Missing data will be filled with zeros by default. The code below shows how to create two objects a and b, the first initially containing only date information and the second with date and time information.
import datetime a = datetime.datetime(2007, 2, 13) b = datetime.datetime(2013, 10, 25, 12, 8, 47) print(a) print(b) 2007-02-13 00:00:00 2013-10-25 12:08:47
You can get the current point in time using two different methods, one of which has already been used before in date. The following code demonstrates a call to the today and now functions that return the current date and time to microsecond accuracy in Python. The print method allows you to display this information as usual.
import datetime a = datetime.datetime.today() b = datetime.datetime.now() print(a) print(b) 2018-11-08 11:12:53.256261 2018-11-08 11:12:53.256270
There is a particular format in which the date and time are output by default, but this representation does not always satisfy user requests. In Python, to convert the date and time to a string in the desired format, use the strftime method with formatting parameters as its argument. As you can see from the example below, special reserved characters, following the percent sign, are used to represent the number of days or minutes. It should be noted that two absolutely identical objects are created here using the today method. However, the strftime function gives them each a different form to display (day, month, and year for variable a, and hour, minute, and second for variable b). After that, the print method displays the information in the format specified earlier.
import datetime a = datetime.datetime.today().strftime("%d.%m.%Y") b = datetime.datetime.today().strftime("%H:%M:%S") print(a) print(b) 08.11.2018 11:41:04
The available format types for output through the console are located in the following table. Here you can find their designations as well as a brief description of what they do.
|%a||the name of the day of the week in abbreviated form|
|%A||full name of the day of the week|
|%w||day of the week as a whole number|
|%d||day of the month as an integer|
|%b||month name in abbreviated form|
|%B||full month name|
|%m||month number in numerical form|
|%y||year number without century|
|%Y||year number in full representation|
|%H||number of hours in 24-hour format|
|%I||number of hours in 12-hour format|
|%p||before noon or after noon in 12-hour format|
|%M||number of minutes as an integer|
|%S||number of seconds as an integer|
|%f||number of microseconds as an integer|
|%z||time zone in UTC format|
|%Z||time zone name|
|%j||day of the year|
|%U||number of week of the year, if counting from Sunday|
|%w||number of week in the year, if counted from Monday|
|%c||local representation of date and time|
|%x||local date display|
|%X||local time representation|
As with time and date, in the datetime class, the user is able to access the individual properties of the created object (years, months, days, hours, minutes, seconds, and microseconds). The following code example demonstrates the output of these values.
import datetime a = datetime.datetime(2015, 3, 27, 8, 12, 24, 34574) print(a.year) print(a.month) print(a.day) print(a.hour) print(a.minute) print(a.second) print(a.microsecond) 2015 3 27 8 12 24 34574
It is also possible to create a new datetime object using two different objects representing time and date. The function combine is used for this purpose. The following example shows how the a and b variables get some values and then are passed to the combine method as two parameters.
from datetime import datetime, date, time a = date(2015, 3, 19) b = time(2, 10, 43) c = datetime.combine(a, b) print(c) 2015-03-19 02:10:43
Using the datetime class, you can easily find the difference between two different dates. The following example demonstrates the creation of two objects. Variable a represents the date passed to it by the now method, and b is set manually using the constructor. By performing a simple operation of finding the difference between objects a and b, a third object c can be obtained. Using the print function allows its properties to be displayed directly by the dot operator.
from datetime import datetime a = datetime.now() b = datetime(2015, 3, 21) c = a - b print(c.days) print(c.seconds) print(c.microseconds) 1328 43219 65190
The list of available operations that you can work with is located in the following table. Here you will find examples of operations and their purpose.
|a + b||sums up the values of the dates a and b|
|a – b||finds the difference between the dates a and b|
|a * i||multiplies the numeric representation of the date a properties by some constant i|
|a // i||divides the numerical representation of the date a by some constant i, the remainder is discarded|
|+a||returns a timedelta object with a fully identical value a|
|-a||returns a timedelta object with a completely opposite value a|
|a > b||returns true if a is greater than b|
|a < b||returns true if a is less than b|
|abs(a)||returns timedelta object with the positive value of all the properties of a|
|str(a)||returns the string representation of the a object in the default format|
|repr(a)||returns the string representation of the object a in the format with negative values|
The timedelta class is designed to easily perform various manipulations with dates and times. You can create an object of this class, using the constructor. The arguments are days, hours, minutes, seconds, microseconds, and weeks, which can be set using direct reference to property names, as shown in the following example. As before, the print method lets you display the date information on the screen and the type function displays the type of the created object.
from datetime import timedelta a = timedelta(days=5, hours=21, minutes=2, seconds=37) print(a) print(type(a)) 5 days, 21:02:37 <class 'datetime.timedelta'>
You can also add different dates, thereby forming a new object. The following example shows how to get the sum of two different dates using the arithmetic operation for variables a and b. The result is assigned to an object called c and then displayed in the usual format using the print method.
from datetime import datetime, timedelta a = datetime(2006, 12, 5) b = timedelta(hours=2, minutes=5, seconds=17) print(a) c = a + b print(c) 2006-12-05 00:00:00 2006-12-05 02:05:17
tzinfo and timezone
The classes tzinfo and timezone are used to handle information that contains timezone information. You can’t create an object of type tzinfo because it’s an abstract class. However, you can use inheritance by creating your own class based on tzinfo. Keep in mind that you have to implement several abstract methods to work with such objects, including utcoffset (local time offset from UTC), dst (adjusting daylight saving time) and the tzname function (time zone name as a string).
from datetime import tzinfo, timedelta, datetime, timezone class UTC0530(tzinfo): def __init__(self, offset=19800, name=None): self.offset = timedelta(seconds=offset) self.name = name or self.__class__.__name__ def utcoffset(self, dt): return self.offset def tzname(self, dt): return self.name def dst(self, dt): return timedelta(0) a = datetime.now(timezone.utc) print(a) b = datetime.now(UTC0530()) print(b) print(b.utcoffset()) print(b.tzname()) print(b.dst()) 2018-11-09 11:00:11.889875+00:00 2018-11-09 16:30:11.890014+05:30 5:30:00 UTC0530 0:00:00
The above program demonstrates the creation of a custom class UTC0530, which describes the methods utcoffset, dst and tzname, and the application of a new type with two objects a and b. Thus, we get the display of time with an offset of +5:30.
Thus, using the classes from the datetime library, you can improve the efficiency of programs that interact with time and date. The possibilities of built-in methods allow you not only to display the necessary information in a convenient format, but also to manipulate them in different ways, for example, by adding or subtracting hours, minutes and seconds.