The datetime and time modules in Python

The  datetime module provides classes for working with date and time. Date and time have countless uses and it’s probably hard to find a production application that doesn’t use them.

1. To create a date() object, you must pass the year, month, and day arguments as follows:

The date object has three (read-only) attributes: year, month, and day.

 

2. The today() method returns a date object representing the current local date:

or

 

3. In Unix, the timestamp expresses the number of seconds since January 1, 1970, 00:00:00 (UTC). This date is called the “Unix epoch”, because it began the counting of time on Unix systems. The timestamp is actually the difference between a particular date (including time) and January 1, 1970, 00:00:00 (UTC), expressed in seconds. To create a date object from a timestamp, we must pass a Unix timestamp to the fromtimestamp method:

Timestamp: 1767643499.6537435
Date: 2026-01-05

Note: The time() function returns the number of seconds from January 1, 1970 to the current moment in the form of a float number.

 

4. The constructor of the time class accepts six arguments (hour, minute, second, microsecond, tzinfo, and fold). Each of these arguments is optional.

Time: 14:53:20.000001
Hour: 14
Minute: 53
Second: 20
Microsecond: 1

 

5. The time module contains the sleep() function, which suspends program execution for a given number of seconds, e.g.:

 

6. In the datetime module, date and time can be represented either as separate objects, or as one object. The class that combines date and time is called datetime. All arguments passed to the constructor go to read-only class attributes. They are year, month, day, hour, minute, second, microsecond, tzinfo, and fold:

 

7. The strftime() method takes only one argument in the form of a string specifying a format that can consist of directives. A directive is a string consisting of the character % (percent) and a lower-case or upper-case letter. Below are some useful directives:

    • %Y – returns the year with the century as a decimal number;
    • %m – returns the month as a zero-padded decimal number;
    • %d – returns the day as a zero-padded decimal number;
    • %H – returns the hour as a zero-padded decimal number;
    • %M – returns the minute as a zero-padded decimal number;
    • %S – returns the second as a zero-padded decimal number.

Example:

or

14:53:00
20/November/04 14:53:00

The %B directive returns the month as the locale’s full name (in our example, it’s November).

The strftime function is also available in the time module. It differs slightly from the strftime methods in the classes provided by the datetime module because, in addition to the format argument, it can also take (optionally) a tuple or struct_time object.

2019/11/04 14:53:00
2026/01/10 21:19:50

You can find all available directives in the time module here.

 

8. Knowing how to create a format can be helpful when using a method called strptime in the datetime class. Unlike the strftime method, it creates a datetime object from a string representing a date and time.

2019-11-04 14:53:00

Be careful, because if the format you specify doesn’t match the date and time in the string, it’ll raise a ValueError.

 

9. It’s possible to perform calculations on date and datetime objects, e.g.:

366 days, 0:00:00
732 days, 0:00:00

The result of the subtraction is returned as a timedelta object that expresses the difference in days between the two dates in the example above.

Note that the difference in hours, minutes, and seconds is also displayed. The timedelta object can be used for further calculations (e.g. you can multiply it by 2).

You can also create an timedelta object yourself. For this purpose, let’s get acquainted with the arguments accepted by the class constructor, which are: days, seconds, microseconds, milliseconds, minutes, hours, and weeks. Each of them is optional and defaults to 0.

16 days, 3:00:00

or

Days: 16
Seconds: 10800
Microseconds: 0

or

16 days, 2:00:00
32 days, 4:00:00
2019-11-05
2019-11-05 18:53:00

 

Example

28 days, 22:00:00

 

11:27:22

 

10. The datetime module provides several methods to create a date object. One of them is the fromisoformat method, which takes a date in the YYYY-MM-DD format compliant with the ISO 8601 standard.

2019-11-04

 

11. Sometimes you may need to replace the year, month, or day with a different value. You can’t do this with the year, month, and day attributes because they’re read-only. In this case, you can use the method named replace().

1991-02-05
1992-01-16

The year, month, and day parameters are optional. You can pass only one parameter to the replace method, e.g., year, or all three as in the example.

 

12. What day of the week is it?

The method called weekday() returns the day of the week as an integer, where 0 is Monday and 6 is Sunday.

0

 

13. The time module provides a function called ctime, which converts the time in seconds since January 1, 1970 (Unix epoch) to a string.

Mon Nov 4 14:53:00 2019

 

Exercise 1

What is the output of the following snippet?

14:39:00

 

Exercise 2

What is the output of the following snippet?

1 day, 0:00:00