Contents
- Determining the number of seconds since the epoch
- Returning the date, time in the usual format
- class time.struct_time
- Returning a Specific Format
- Postpone a thread for a certain number of seconds
- Get local time
- Return struct_time in UTC based on number of seconds since epoch
- Return the number of seconds since the start of the epoch with automatic conversion to local time
- Output date from 9 numbers that refer to struct_time
- Getting time and date based on Python string
Almost any program uses time. In Python, a separate library has been developed for this – timeused to perform a variety of actions with it. To make it work, it must first be declared at the beginning of the code. This line is used for this:
import time
Let’s consider different options on how to use this module correctly in practice.
Determining the number of seconds since the epoch
To accomplish this task, there is a function time() that takes no parameters. Its return value is how many seconds have passed since January 1, 1970. In Python, this time is called the start of an epoch. At least in operating systems of the Unix family.
As for Windows, the date is the same, but there may be problems with negative values that were before this date.
The time zone used is UTC.
import time
seconds = time.time()
print(“Seconds since epoch =”, seconds)
The complexity of this function is that it does not display exactly the date, but only the number of seconds. To convert to the format familiar to everyone, you need to use accurate information. For this, the function is used time.ctime().
Returning the date, time in the usual format
To return the time in the usual format, there is a method time.ctime(). The brackets indicate a variable or a number indicating the number of seconds that have passed since the start of the epoch. This method returns all date and time characteristics, including the date, year, number of hours, minutes, seconds, and day of the week.
This function can also be used without arguments. In this case, it returns the current date, time, and so on.
Here is a code snippet that demonstrates this.
import time
print(time.ctime())
Tue Oct 23 10:18:23 2018
The last line is what is printed to the console where the Python interpreter is running. The method automatically formats the received number of seconds into a user-familiar form. True, all the elements described above are rarely used. As a rule, you need to get either only the time, or only today’s date. For this, a separate function is used – strftime(). But before we consider it, we need to parse the class time.struct_time.
class time.struct_time
This is a category of arguments that can be accepted by a range of methods. It doesn’t have any options. It is a tuple with a named interface. Simply put, the elements of this class can be accessed both by name and by index number.
It consists of the following attributes.
Attention! Unlike a number of other programming languages, here the month can range from 1 to 12, and not from zero to 11.
Returning a Specific Format
Using the function strftime() you can get the year, month, day, hour, minutes, seconds individually and return them to a text string. Then it can be printed to the user using the function print () or otherwise processed.
As an argument, a function can take any variable that takes a value returned by other functions of this module. For example, you can transfer the local time to it (it will be discussed later), from which it will pull out the necessary data.
Here is the code snippet where we do it.
import time
named_tuple = time.localtime() # get struct_time
time_string = time.strftime(«%m/%d/%Y, %H:%M:%S», named_tuple)
print(time_string)
If you run this code, the current date and time will be displayed. The format and sequence of elements can be changed. They are as follows:
- %Y is the year.
- %m is the month.
- %d – day.
- %H – time.
- %M – minutes.
- %S – second.
Accordingly, you can make it so that the output is exclusively of the month and day. To do this, you simply do not need to give a command to display the year. That is, write in the above formula as an argument %m/%d, and that’s it. Or vice versa, %d/%m.
In fact, the number of string literals is much larger. Here is a table where they are described in detail.
Postpone a thread for a certain number of seconds
For this, the function is used sleep (). A fairly large block of programming tasks is associated with the passage of time. Sometimes you have to postpone the next step for a certain time. For example, if you need to interact with a database that takes a certain amount of time to process.
As an argument, the method uses a value that expresses the number of seconds to delay the next step from the algorithm.
For example, in this snippet, the delay is 10 seconds.
import time
pause = 10
print(«Program started…»)
time.sleep(pause)
print(str(pause) + » seconds passed.»)
As a result, we will get this:
Program started…
10 seconds passed.
As we can see from the output, the program first reports that it has started. And after ten seconds, she wrote that this time had passed.
The function allows you to specify the duration of the pause in milliseconds. To do this, we use fractional values of the function argument sleep. For example, 0,1. This means that the delay will be 100 milliseconds.
Get local time
Using the localtime() function, the program gets the number of seconds since the start of the epoch in a specific time zone.
Let’s give an example code for clarity.
import time
result = time.localtime(1575721830)
print(“result:”, result)
print(«nгод:», result.tm_year)
print(«tm_hour:», result.tm_hour)
Return struct_time in UTC based on number of seconds since epoch
This task is achieved using the time.gmtime(). method. It will be clearer if we give an example.
import time
result = time.gmtime(1575721830)
print(“result:”, result)
print(«nгод:», result.tm_year)
print(«tm_hour:», result.tm_hour)
If you turn on this sequence of actions, then a set of elements related to time, year and time zone will be displayed.
Return the number of seconds since the start of the epoch with automatic conversion to local time
If you are faced with such a task, it is implemented using the method mktime(), which takes struct_time. After that, it performs the reverse action of the function localtime(). That is, it converts the time according to the local time zone into the number of seconds that have passed since the start of the epoch, adjusted for the time zone.
The mktime() and localtime() functions are closely intertwined. This code snippet clearly demonstrates this. Let’s take a look at it to understand more deeply how it works.
import time
seconds = 1575721830
# returns struct_time
t = time.localtime(seconds)
print(«t1: «, t)
# returns seconds from struct_time
s = time.mktime(t)
print(«ns:», seconds)
We see that the variable seconds has been assigned 1575721830 seconds since the epoch. First, the program gets the exact date, time and other parameters, based on this value, put it in a variable t, and then converts its contents into a variable s.
After that beats off a new line and displays the number of seconds in the console. You can check that it will be the same number that was assigned to the seconds variable.
Output date from 9 numbers that refer to struct_time
Suppose we have 9 numbers representing the year, month, date, day of the week and a number of other values, and we need to combine them into one string. For this, the function is used asctime(). She accepts or ready struct_time, or any other tuple of 9 values that stands for the same. After that, a string is returned, which is a date, time, and a number of other parameters.
It is very convenient to use this method in order to bring disparate user-specified data into a single variable..
For example, it may be a program where the user specifies separately the day, month, year, day of the week, and other data regarding registration for an event. After that, the information received is entered into the database and then issued to another person who requests it.
Getting time and date based on Python string
Suppose the user has specified disparate data, and we need to combine them into one line in the format that the person entered, and then make a copy to another variable, and rebuild it into a standard format there. For this, the function is used time.strptime().
It takes a variable in which this value is specified, and returns the already familiar to us struct_time.
For clarity, we will write such a program.
import time
time_string = «15 June, 2019»
result = time.strptime(time_string, «%d %B, %Y»)
print(result)
Guess what the output will be? Try to guess without looking at the bottom line. And then check the answer.
time.struct_time(tm_year=2019, tm_mon=6, tm_mday=15, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=166, tm_isdst=-1)
In a word, working with dates and times in Python is not difficult at all. It is enough to follow these instructions, and everything will work out. Using the Library time the user gets a huge number of opportunities for working with time, such as:
- Suspend program execution for a specified amount of time.
- Show the time that has passed since the epoch, in seconds. This information can be used to sum up time or perform other mathematical operations on it.
- Convert to a convenient format. Moreover, the programmer himself can set which elements will be displayed and in what sequence.
There are also a number of other possibilities, but today we have analyzed the most basic ones. They will come in handy in almost any program that somehow works with time. Good luck.