Python Time and Tricks By albro

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@albro·
0.000 HBD
Python Time and Tricks By albro
<center>![Python Time and Tricks](https://files.peakd.com/file/peakd-hive/albro/EogQnwFuxaNtt9x2u6pPBBACNzbNCDoUUZi7zLRZFFhaCYzUohPK5PVfJBNHQFrM55G.jpg)</center>

<p>The element of time has various uses in the development of different programs. We may want to check when the request was sent. Or create an interruption during the execution of the program. In this post, I'll deal with working with <strong>time in Python</strong>. I use the <strong><code>time</code> library in Python</strong> and work with different functions.</p>
<h3>Time in computer systems</h3>
<p>As you may know, time in computer systems is measured in seconds. All times have a time origin. The origin of computer time is <strong>January 1, 1970 at 00:00 AM</strong>. The time in the computer is calculated as seconds that have passed since the original time. It can then be converted to hours and dates by special arithmetic conversion.</p>
<p>There are many modules and libraries for working with time in Python. They are mostly used for a specific application in programming.</p>
<p>One of the main modules provided by default with Python is the <code>time</code> library.</p>
<p>This library provides us with various functions to get the current time of the system, calculate times and create interrupts.</p>
<p>Next, I will examine working with the <code>time</code> module in Python.</p>
<h3><code>time</code> library for working with time in Python</h3>
<p>To use this module, we must first enter it into the program.</p>
<pre><code>import time</code></pre>
<p>Now I can do things related to time by calling different functions on <code>time</code>.</p>
<p><strong>Get system time</strong></p>
<p>The first and one of the most used functions in this module is the <code>time()</code> function. This function outputs the current system time. The output is in the form of a <code>float</code> and it is the elapsed seconds from the time origin.</p>
<pre><code>time.time()</code></pre>

<center>![python time() function](https://files.peakd.com/file/peakd-hive/albro/23u6YdYXq1zVKzkk9vmSDojMBizQ2C8GA8b8bFhysCNY1vSCnsLFkcFUnDQY4zJ8PnYVf.png)</center>

<p><strong>Current time with today's date</strong></p>
<p>There is another function in Python's <code>time</code> module called <code>localtime()</code>. This function returns an object of type <code>time.struct_time</code>. This object has properties with the following name and information.</p>
<pre><code>time.localtime()<br />
# time.struct_time(tm_year=2023, tm_mon=5, tm_mday=19, tm_hour=12,
#                  tm_min=14, tm_sec=26, tm_wday=4, tm_yday=139, tm_isdst=1)</code></pre>
<p>The properties of this object are:</p>
<ul>
<li><code>tm_year</code> : Year</li>
<li><code>tm_mon</code> : Current month</li>
<li><code>tm_mday</code> : number of the day of the month (specifying the number of the month</li>
<li><code>tm_hour</code> : Current hour</li>
<li><code>tm_min</code> : minute of current time</li>
<li><code>tm_sec</code> : seconds of time</li>
<li><code>tm_wday</code> : counting the day of the week (the most recent day of the current week, including Monday, equal to 0)</li>
<li><code>tm_yday</code> : counting the day of the year (how many days of the year is today?)</li>
<li><code>tm_isdst</code> : specifying whether daylight saving time is active</li>
</ul>
<p>We can store this object in a variable and use its properties. For example, in the code below, I have printed the year and the day counter of the year.</p>
<pre><code>now = time.localtime()<br />
print( now.tm_year)   # 2023<br />
print( now.tm_yday)   # 139</code></pre>

<center>![python-localtime()-function.png](https://files.peakd.com/file/peakd-hive/albro/23tHbkj8CLsSYa5k6vagJpSgJtNxBu2D9knvoLvRYetqCioZnf664ZmFo5JAnqx8Ax4eU.png)</center>

<p><strong>Convert seconds to hours and date of the day</strong></p>
<p>We saw that with the help of the <code>time()</code> function, we can get and keep the time in seconds. Now we may have a numerical value (seconds) that we want to convert to time.</p>
<p><i>To convert seconds to days and hours and minutes in Python</i>, we will use the <code>ctime()</code> function in the Python time library.</p>
<p>If we don't give it any value as input to the function, it will output the current time by default.</p>
<pre><code>time.time()
# 1684483432.2221847
time.ctime()
# 'Fri May 19 12:33:54 2023'
time.ctime(1684483432.2221847)
# 'Fri May 19 12:33:52 2023'</code></pre>

<center>![python ctime() function](https://files.peakd.com/file/peakd-hive/albro/Eo8ZeGF6xcy5BPFXxJQLLZuWUYN2wwyctcdL23xyqUTbttq4LyceE7qH8g7VSqxM8LS.png)</center>

<p><strong>Convert specific time and date to seconds</strong></p>
<p>Suppose we have a specific date and time and want to calculate its second equivalent. For this, we will use the <code>mktime()</code> function.</p>
<p>This function takes a struct_time object as input. (Its structure is exactly the same as the output structure of the <code>localtime()</code> function.)</p>
<pre><code>import time
t = time.localtime()
time.mktime(t)
# 1684483966.0</code></pre>
<p><strong><i>Basically, this function works the opposite of the <code>localtime()</code> function.</i></strong></p>

<center>![Python Time Tricks](https://files.peakd.com/file/peakd-hive/albro/Ep3X6TbCBUFxaCeTUxVzkhWLMqQcMv2c8mwm7a9BHgzkQtxsa8sRxz7BGATaUwy8D5s.jpg)</center>

<p><strong>Print time with special time format in Python</strong></p>
<p>Most of the time, when working with time in Python, we need to display a time in a specific format. For this, you can use the <code>strftime()</code> function.</p>
<p>This function has two inputs.</p>
<ul>
<li>The first input is a string specifying our desired format.</li>
<li>The second input is an object of the <code>struct_time</code> class that specifies the time we want.</li>
</ul>
<pre><code>current_time = time.localtime()
time_string = time.strftime( "%m/%d/%Y %H:%M:%S", current_time )
print(time_string)
# 05/19/2023 12:49:17</code></pre>

<center>![python strftime() function](https://files.peakd.com/file/peakd-hive/albro/23uFwWZh7HW9WvPyHQhWm5CVPoSmdio6GXobVbQt2cH1k5erZsncRWMRQnoVETaPCKXLp.png)</center>

<p><strong>Convert time in seconds format</strong></p>
<p>If we want to do the opposite of the previous operation, we will use the <code>strptime()</code> function. This function takes two inputs from us.</p>
<ul>
<li>The first input is a string specifying the input time format.</li>
<li>The second input is the string and time we want.</li>
</ul>
<pre><code>time_string = "19 May 2023"
result = time.strptime( time_string, "%d %b %Y" )
print(result)<br />
# time.struct_time(tm_year=2023, tm_mon=5, tm_mday=19,
#                  tm_hour=0, tm_min=0, tm_sec=0,
#                  tm_wday=4, tm_yday=139, tm_isdst=-1)</code></pre>
<p>If the hours are not specified in the entered value, they are assumed to be zero.</p>
<h3>Creating an interruption with the <code>sleep</code> function</h3>
<p>Sometimes in the development of programs, we need to stop the program for a certain period of time. For example, a task must be done 45 seconds after the completion of another activity.
<p>Or in the programming of web crawlers to avoid blocking the activity of the robot, it is better to randomly interrupt the crawler.</p>
<p>When you communicate with the $Hive blockchain, you must create a certain interrupt between each comment for actions such as sending comments. Or when you want to trade, you need to have an interruption after the value of each token!</p>
<p>To interrupt the running program, the <code>sleep()</code> function is used in the <code>time</code> module.</p>
<p>The input of this function is a number that specifies the amount of seconds to interrupt the execution.</p>
<pre><code>time.sleep( 45 )</code></pre>
<p><strong>Definition of random delay in Python</strong></p>
<p>In order to define the program execution delay (interruption) randomly, you can easily use a <code>Random</code> value.</p>
<p>The following code takes a random 1-2 minute break each time the <a href="https://peakd.com/hive-169321/@albro/python-loops-and-tricks-by-albro">Python loop</a> executes.</p>
<pre><code>import time
import random<br />
while True:
    # do something here
    time.sleep( random.randint( 60, 120 ) )</code></pre>
<h3>Calculation of program execution time in Python</h3>
<p>One of the most common uses of time tricks in Python by programmers is to calculate the execution time of the program.</p>
<p>With a simple trick and using the <code>time</code> module in Python, we will be able to accurately calculate the duration of the code execution.</p>
<p>For this, we must register the current time using the <code>time()</code> function before starting the desired piece of code and do the same after execution.</p>
<p>The difference between these two times will be equal to the program execution time.</p>
<p>For example, suppose we want to get the execution time of the following program.</p>
<p>In this simple program, we add the numbers 1 to 500 together with a <code>for</code> loop and print them in the output.</p>
<pre><code>sum = 0
for n in range(1,500):
    sum += n
print(sum)</code></pre>
<p>To calculate the execution time, before starting the <code>for</code> loop, we put the current time in the <code>start</code> variable by calling the <code>time()</code> function.</p>
<p>At the end, by calling the same function again, we subtract the start time from it and display it in the output.</p>
<pre><code>import time<br />
start = time.time()
sum = 0
for n in range(1,500):
    sum += n
print(sum)<br />
print("Run Time: " + str( time.time() - start ))</code></pre>
<p>The program execution time for me was about 0.022 seconds!</p>
<pre><code>124750
Run Time: 0.02178672218322754</code></pre>
<p>So easily we were able to calculate the execution time of the program in Python using the tricks of working with time that we learned.</p>
<h3>Summary: time module</h3>
<p>In this post, I talked about the time library in the Python programming language. Using its various functions, we took the current time of the system and converted different times to each other.</p>
<p>At first, we learned about the use of the <code>time()</code> function, which outputs the current time of the system in the form of elapsed seconds. Then I converted this value to a readable format using the <code>strftime()</code> function.</p>
<p>Next, I interrupted the execution of my program with the <code>sleep()</code> function.</p>
<p><strong>What techniques do you use to work with time in Python? Which function or method is empty in this post? The comments section is for your comments and questions.</strong></p>
👍 , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,