logo

tiempo.dormir() en Python

La función Python time sleep() suspende la ejecución durante el número de segundos indicado.

Sintaxis de tiempo de sueño()

Sintaxis: dormir (seg)

Parámetros:



    sec: Número de segundos durante los cuales se requiere detener el código.

Devoluciones : VACÍO.

A veces, es necesario detener el flujo del programa para que puedan realizarse otras ejecuciones o simplemente por la utilidad requerida. sleep() puede resultar útil en tal situación, ya que proporciona una forma precisa y flexible de detener el flujo de código durante cualquier período de tiempo. Esta función analiza la información de esta función.

Ejemplo 1: Crear un retraso de tiempo en segundos

La hora de inicio y la hora de finalización se imprimirán con un retraso de 6 segundos.

encontrar mi iphone desde android

Python3




import> time> # printing the start time> print>(>'The time of code execution begin is : '>, time.ctime())> # using sleep() to hault the code execution> time.sleep(>6>)> # printing the end time> print>(>'The time of code execution end is : '>, time.ctime())>

>

>

Producción:

The time of code execution begin is : Mon Apr 9 20:57:10 2018 The time of code execution end is : Mon Apr 9 20:57:16 2018>

Ejemplo 2: Crear un retraso de tiempo en minutos

La lista se mostrará después de un retraso de 3 minutos.

Python3




import> time> # creating and Initializing a list> Languages>=> [>'Java'>,>'C++'>,>'Python'>,>'Javascript'>,> >'C#'>,>'C'>,>'Kotlin'>]> # creating a time delay of 3 minutes> time.sleep(>3> *> 60>)> print>(Languages)>

>

>

Producción:

Después de un retraso de 3 minutos, la lista se mostrará como:

['Java', 'C++', 'Python', 'Javascript', 'C#', 'C', 'Kotlin']>

Aplicación de time.sleep()

Hay muchas aplicaciones para las que se utiliza sleep(). Ya sea que la ejecución del hilo en segundo plano se repita a intervalos regulares, esto se puede implementar con la ayuda de sleep(). Otra aplicación popular utiliza sleep() para imprimir las palabras letra por letra para una buena interfaz de usuario. Este último está representado en el código siguiente.

Ejemplo 1: Creando un retraso de tiempo en el bucle de pitón

Python3




import> time> # initializing string> strn>=> 'techcodeview.com'> # printing geeksforgeeks after delay> # of each character> for> i>in> range>(>0>,>len>(strn)):> >print>(strn[i], end>=>'')> >time.sleep(>2>)>

>

>

Producción:

GeeksForGeeks>

Nota: El efecto visible de sleep() se puede ver en el editor local.

Ejemplo 2: Creando un retraso de tiempo en Pitón Lista

Python3

son ejemplos de modelos




# importing time package> import> time> # creating a time delay of 5 seconds> time.sleep(>5>)> # creating and Initializing a list> myList>=> [>'Jai'>,>'Shree'>,>'RAM'>,>5>,>'August'>,>2020>]> # the list will be displayed after the> # delay of 5 seconds> print>(myList)>

>

>

Producción:

Después de un retraso de 5 segundos, obtendremos el resultado como:

['Jai', 'Shree', 'RAM', 5, 'August', 2020]>

Ejemplo 3: Creando un retraso de tiempo en Pitón tupla

Python3




# importing time package> import> time> # creating a time delay of 4 seconds> time.sleep(>4>)> # creating and Initializing a tuple> mytuple>=> (>'Anil Kumbl'>,>'Sachin Tendulkar'>,>'Sunil Gavaskar'>,> >'Rahul Dravid'>,>'Mahendra Singh Dhoni'>,> >'Dennis Lillee'>,>'Muttiah Muralitharan'>,>'Shane Warne'>)> # the tuple will be displayed after the delay of 4 seconds> print>(mytuple)>

>

>

Producción:

Después de un retraso de 4 segundos, obtendremos el resultado como:

('Anil Kumbl', 'Sachin Tendulkar', 'Sunil Gavaskar', 'Rahul Dravid', 'Mahendra Singh Dhoni', 'Dennis Lillee', 'Muttiah Muralitharan', 'Shane Warne')>

Ejemplo 4: Retraso de tiempo en un Comprensión de listas

Python3




longitud de la cadena bash
# importing time package> import> time> # creating and Initializing a list> cricketers>=> [>'Anil Kumble'>,>'Sachin Tendulkar'>,>'Sunil Gavaskar'>,> >'Rahul Dravid'>,>'Mahendra Singh Dhoni'>,> >'Dennis Lillee'>,>'Muttiah Muralitharan'>,>'Shane Warne'>]> # time delay of 7 seconds is created> # after every 7 seconds item of list gets displayed> cricketers>=> [(time.sleep(>7>),>print>(cric))>for> cric>in> cricketers]>

>

>

Producción:

Cada 7 segundos, los elementos de la lista se mostrarán como:

Anil Kumble Sachin Tendulkar Sunil Gavaskar Rahul Dravid Mahendra Singh Dhoni Dennis Lillee Muttiah Muralitharan Shane Warne>

Ejemplo 5: Creando Múltiple Retrasos de tiempo

Python3




# importing time package> import> time> # creating and Initializing a list> Languages>=> [>'Java'>,>'C++'>,>'Python'>,>'Javascript'>,>'C#'>,>'C'>,>'Kotlin'>]> # creating a time delay of 5 seconds> time.sleep(>5>)> # the list will be displayed after the delay of 5 seconds> print>(Languages)> for> lan>in> Languages:> ># creating a time delay of 13 seconds> >time.sleep(>13>)> ># After every 13 seconds an item of list will be displayed> >print>(lan)>

>

>

Producción:

Después de un retraso de 5 segundos, la lista se mostrará como:

['Java', 'C++', 'Python', 'Javascript', 'C#', 'C', 'Kotlin']>

Luego, cada 13 segundos, los elementos de la lista se mostrarán como:

Java C++ Python Javascript C# C Kotlin>