Get up to 80 % extra points for free! More info:

Date and Time in Python

In the last lesson, Type System and Type Hints in Python, we learned how to type variables and functions in Python and how to create new types.

In this lesson, I would like to explain how we work in Python to determine and use the current date and time. This can be useful to us, for example, when passing information to the user of our applications or when creating all sorts of timed events.

We have already talked about how to use libraries in previous lessons. Today we'll focus mainly on the time library (working with time) and the calendar library (date/calendar processing).

time

The first and very useful library is the time library. It'll provide us with information about the current time and date, and will also help us with a clear print for users. We'll first import the library:

import time

In order to use the time module, we must always import it like this at the beginning of the program. And now to the functions themselves.

time()

The basic function of the time module is the time() function. Its return value (referred to as a tick) may seem unreadable at first. It's a decimal number (float) showing the number of seconds that have elapsed since 1/1/1970. Let's try to print this value:

#!/usr/bin/env python3

import time
print(time.time())

The value as such has many uses. For example, if we create a variable with the current time value anywhere in our program, we can later create a second "more current" value. Then, after subtracting both values, we find out how much time has elapsed between the individual points in the program. For example, you can create a timed while loop in a similar way:

import time

startTime = time.time()
while (time.time()-startTime) <= 3:
    # program code that'll be running for 3 seconds

Similarly, time.clock() method can be used. It's different from time.time() in a way that its value indicates the number of seconds that have elapsed since the start of the current process (our program itself).

localtime()

This method provides us with current information from the user's environment. All information is in a special struct_time object. This object (time structure) consists of 9 numbers:

Index Property Value
0 Year 2019
1 Month 1 - 12
2 Day 1 - 31
3 Hour 0 - 23
4 Minute 0 - 59
5 Second 0 - 61
6 Day of the week 0 - 6 (0 = Monday)
7 Day of the year 1 - 366 (Julian day)
8 Daylight saving 0 / 1

First, let's print the whole structure:

#!/usr/bin/env python3

import time
print(time.localtime())

One way to get data from this object is to select it directly using an index:

#!/usr/bin/env python3

import time

local = time.localtime()
print("Today is {}. {}. {}.".format(local[2], local[1], local[0]))

This way we can create any formatting style we want.

asctime()

We can use the asctime() function for concisely and legibly defined formatting. We insert a time object (struct_time) into the function, which returns a text (string) with printed values in a predetermined order:

#!/usr/bin/env python3

import time

local = time.localtime()
print("Date and time: {} ".format(time.asctime(local)))

sleep()

The useful function sleep() allows us to put our program on hold for a precise period of time, which we pass as a parameter. Let's try it:

#!/usr/bin/env python3

import time

print("Start")
time.sleep(3) #the program stops for 3 seconds ("sleeps")
print("End")

These were the basic functions of the time library that we can encounter in our work. For deeper research, I recommend searching for official descriptions of the library itself.

calendar

The second library we'll introduce today is calendar, which adds new options for formatting the data printing for users. We must always import new modules at the beginning:

import calendar

month()

The first nice method is month(). When using, we must specify which year and month we wish to choose. The function then returns a few lines of text with a very coherent calendar:

#!/usr/bin/env python3

import calendar

month = calendar.month(2019, 11)
print("This month's calendar")
print(month)

If we want a similar calendar for the whole year, we can use the calendar() function and pass it the year as a parameter. But it returns a large amount of text. So it's probably better to use individual months, for which we can make our own changes, if necessary.

monthrange(year, month)

If we need more information about a given month, we'll put monthrange() to a good use. We get two numbers from it in the form (what day of the week is the first day of the month, the total number of days in the month):

#!/usr/bin/env python3

import calendar

mr = calendar.monthrange(2019, 11)
print(mr)

When determining the day of the week, we must pay attention to 2 things:

  • Monday has an index of 0 and Sunday has an index of 6
  • January has an index of 1, December has an index of 12

weekday()

The weekday() function will be useful if we want to quickly find out what day of the week was/is/will be a given date. The parameters are year, month and day. The function returns a single number, the index of the day of the week corresponding to the specified date:

#!/usr/bin/env python3

import calendar

#List of days of the week
days_of_week={0:"Monday", 1:"Tuesday", 2:"Wednesday", 3:"Thursday", 4:"Friday", 5:"Saturday", 6:"Sunday"}

day5 = calendar.weekday(2019, 11, 5)
print("5 November 2019 is " + days_of_week[day5])

isleap()

If we want to quickly find out whether a given year is a leap year or not, the isleap() function will help us. The function returns only True / False.

#!/usr/bin/env python3

import calendar

leap1 = calendar.isleap(2019)
print("Is 2019 a leap year? {}".format(leap1))

leap2 = calendar.isleap(2020)
print("Is 2020 a leap year? {}".format(leap2))

This summarizes the necessary modules to help us work with the date and calendar.

Curiosity - The Year 2038

In the time library chapter, we mentioned the date 1/1/1970. This is the date the UNIX operating system was born.

This counter, as I mentioned earlier, shows the number of seconds since the beginning of the era. The countdown runs in Int32 type numbers. What does Int32 mean? Whatever number we show, the program has it stored using a series of 32 bits (zeros and ones).

But this fact carries one problem. Since these are "only" 32 bits, there's an actual limit to the numbers that can be expressed in this way. More specifically from -2 147 483 648 to 2 147 483 647.

And the same limit exists for our timer. Many people are already aware of this problem. We can read more about this on the Internet under the name "Year 2038 problem".

If this problem is not resolved by the time we reach the limit, a very special kind of situation will arise for our computers and also for us. Instead of January 19, 2038, we would wake up to the afternoon of December 13, 1901 8-) .

Simulation of the last seconds of the countdown - Object-Oriented Programming in Python

Year 2038 problem - Wikipedia. [online]. Available from: https://en.wikipedia.org/...2038_problem


 

Previous article
Type System and Type Hints in Python
All articles in this section
Object-Oriented Programming in Python
Article has been written for you by Shift
Avatar
User rating:
No one has rated this quite yet, be the first one!
As an author I'm interested mainly in industry automation. I'm also writing music and literature. In my spare time I'm working on a few games in Game Maker Studio.
Activities