Python time function example

Модуль time в Python

В Python есть модуль time , который используется для решения задач, связанных со временем. Для использования определенных в нем функций необходимо сначала его импортировать:

Дальше перечислены самые распространенные функции, связанные со временем.

Python time.time()

Функция time() возвращает число секунд, прошедших с начала эпохи. Для операционных систем Unix 1 января 1970, 00:00:00 (UTC) — начало эпохи (момент, с которого время пошло).

import time seconds = time.time() print("Секунды с начала эпохи token punctuation">, seconds) 

Python time.ctime()

Функция time.ctime() принимает в качестве аргумента количество секунд, прошедших с начала эпохи, и возвращает строку, представляющую собой местное время.

import time # секунды прошли с эпох seconds = 1575721830.711298 local_time = time.ctime(seconds) print("Местное время:", local_time) 

Если запустить программу, то вывод будет выглядеть так:

Местное время: Sat Dec 7 14:31:36 2019 

Python time.sleep()

Функция sleep() откладывает исполнение текущего потока на данное количество секунд.

import time print("Сейчас.") time.sleep(2.4) print("Через 2.4 секунды.") 

Прежде чем переходить к другим функциям, связанных со временем, нужно вкратце разобраться с классом time.struct_time .

Класс time.struct_time

Некоторые функции в модуле time , такие как gmtime() , asctime() и другие, принимают объект time.struct_time в качестве аргумента или возвращают его.

Вот пример объекта time.struct_time .

Индекс Атрибут Значения
0 tm_year 0000, …, 2019, …, 9999
1 tm_mon 1, 2, …, 12
2 tm_mday 1, 2, …, 31
3 tm_hour 0, 1, …, 23
4 tm_min 0, 1, …, 59
5 tm_sec 0, 1, …, 61
6 tm_wday 0, 1, …, 6; Monday is 0
7 tm_yday 1, 2, …, 366
8 tm_isdst 0, 1 or -1

К значениям (элементам) объекта time.struct_time доступ можно получить как с помощью индексов, так и через атрибуты.

Python time.localtime()

Функция localtime() принимает в качестве аргумента количество секунд, прошедших с начала эпохи, и возвращает stuct_time в локальном времени.

import time result = time.localtime(1575721830) print("результат:", result) print("\nгод:", result.tm_year) print("tm_hour:", result.tm_hour) 

Вывод этой программы будет следующим:

result: time.struct_time(tm_year=2019, tm_mon=12, tm_mday=7, tm_hour=14, tm_min=30, tm_sec=30, tm_wday=5, tm_yday=341, tm_isdst=0) year: 2019 tm_hour: 14 

Если localtime() передан аргумент None , то вернется значение из time() .

Читайте также:  Python and mysql database

Python time.gmtime()

Функция gmtime() принимает в качестве аргумента количество секунд, прошедших с начала эпохи и возвращает struct_time в UTC.

import time result = time.gmtime(1575721830) print("результат:", result) print("\nгод:", result.tm_year) print("tm_hour:", result.tm_hour) 

Вывод этой программы будет следующим:

result: time.struct_time(tm_year=2019, tm_mon=12, tm_mday=7, tm_hour=12, tm_min=30, tm_sec=30, tm_wday=5, tm_yday=341, tm_isdst=0) year: 2019 tm_hour: 12 

Если gmtime() передан аргумент None , то вернется значение time() .

Python time.mktime()

Функция mktime() принимает struct_time (или кортеж, содержащий 9 значений, относящихся к struct_time ) в качестве аргумента и возвращает количество секунд, прошедших с начала эпохи, в местном времени. Это функция, обратная localtime() .

import time t = (2019, 12, 7, 14, 30, 30, 5, 341, 0) local_time = time.mktime(t) print("Местное время:", local_time) 

Следующий пример показывает, как связаны mktime() и localtime() .

import time seconds = 1575721830 # возвращает struct_time t = time.localtime(seconds) print("t1: ", t) # возвращает секунды из struct_time s = time.mktime(t) print("\ns:", seconds) 
t1: time.struct_time(tm_year=2019, tm_mon=12, tm_mday=7, tm_hour=14, tm_min=30, tm_sec=30, tm_wday=5, tm_yday=341, tm_isdst=0) s: 1575721830 

Python time.asctime()

Функция asctime() принимает struct_time (или кортеж, содержащий 9 значений, относящихся к struct_time ) в качестве аргумента и возвращает строку, представляющую собой дату.

import time t = (2019, 12, 7, 14, 30, 30, 5, 341, 0) result = time.asctime(t) print("Результат:", result) 
Результат: Sat Dec 7 14:30:30 2019 

Python time.strftime()

Функция strftime принимает stuct_time (или соответствующий кортеж) в качестве аргумента и возвращает строку с датой в зависимости от использованного формата. Например:

import time named_tuple = time.localtime() # получить struct_time time_string = time.strftime("%m/%d/%Y, %H:%M:%S", named_tuple) print(time_string) 

Здесь %Y , %m , %d , %H и другие — элементы форматирования.

  • %Y — год [0001,…, 2019, 2020,…, 9999]
  • %m — месяц [01, 02, …, 11, 12]
  • %d — день [01, 02, …, 30, 31]
  • %H — час [00, 01, …, 22, 23
  • %M — минута [00, 01, …, 58, 59]
  • %S — секунда [00, 01, …, 58, 61]

Python time.strptime()

Функция strptime() делает разбор строки python, в которой упоминается время и возвращает struct_time .

import time time_string = "15 June, 2019" result = time.strptime(time_string, "%d %B, %Y") print(result) 
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) 

Источник

Читайте также:  Get label name php

Python time Module

The time module in Python provides functions for handling time-related tasks.

The time-related tasks includes,

  • reading the current time
  • formatting time
  • sleeping for a specified number of seconds and so on.

Python time.time() Function

In Python, the time() function returns the number of seconds passed since epoch (the point where time begins).

For the Unix system, January 1, 1970, 00:00:00 at UTC is epoch.

# import the time module import time # get the current time in seconds since the epoch seconds = time.time() print("Seconds since epoch ctime">Python time.ctime() Function 

The time.ctime() function in Python takes seconds passed since epoch as an argument and returns a string representing local time.

import time # seconds passed since epoch seconds = 1672215379.5045543 # convert the time in seconds since the epoch to a readable format local_time = time.ctime(seconds) print("Local time:", local_time)
Local time: Wed Dec 28 08:16:19 2022

Here, we have used the time.ctime() function to convert the time in seconds since the epoch to a readable format, and then printed the result.

Python time.sleep() Function

The sleep() function suspends (delays) execution of the current thread for the given number of seconds.

import time print("Printed immediately.") time.sleep(2.4) print("Printed after 2.4 seconds.")
Printed immediately. Printed after 2.4 seconds.

Here's how this program works:

  • "Printed immediately" is printed
  • time.sleep(2.4) suspends execution for 2.4 seconds.
  • "Printed after 2.4 seconds" is printed.

To learn more about sleep() , please visit: Python sleep().

Python time.localtime() Function

The localtime() function takes the number of seconds passed since epoch as an argument and returns struct_time (a tuple containing 9 elements corresponding to struct_time ) in local time.

import time result = time.localtime(1672214933) print("result:", result) print("\nyear:", result.tm_year) print("tm_hour:", result.tm_hour)
result: time.struct_time(tm_year=2022, tm_mon=12, tm_mday=28, tm_hour=8, tm_min=8, tm_sec=53, tm_wday=2, tm_yday=362, tm_isdst=0) year: 2022 tm_hour: 8

Here, if no argument or None is passed to localtime() , the value returned by time() is used.

Python time.gmtime() Function

The gmtime() function takes the number of seconds passed since epoch as an argument and returns struct_time in UTC.

import time result = time.gmtime(1672214933) print("result:", result) print("\nyear:", result.tm_year) print("tm_hour:", result.tm_hour)
result: time.struct_time(tm_year=2022, tm_mon=12, tm_mday=28, tm_hour=8, tm_min=8, tm_sec=53, tm_wday=2, tm_yday=362, tm_isdst=0) year: 2022 tm_hour: 8

Here, if no argument or None is passed to gmtime() , the value returned by time() is used.

Python time.mktime() Function

The mktime() function takes struct_time (a tuple containing 9 elements corresponding to struct_time ) as an argument and returns the seconds passed since epoch in local time.

The struct_time has the following structure:

(year, month, day, hour, minute, second, weekday, day of the year, daylight saving)
import time time_tuple = (2022, 12, 28, 8, 44, 4, 4, 362, 0) # convert time_tuple to seconds since epoch seconds = time.mktime(time_tuple) print(seconds) # Output: 1672217044.0

Here, we have converted the time_tuple to seconds since the epoch.

Python time.asctime() Function

In Python, the asctime() function takes struct_time as an argument and returns a string representing it.

Similar to mktime() , the time_tuple has the following structure:

(year, month, day, hour, minute, second, weekday, day of the year, daylight saving)
import time t = (2022, 12, 28, 8, 44, 4, 4, 362, 0) result = time.asctime(t) print("Result:", result) # Output: Result: Fri Dec 28 08:44:04 2022

Here, we can see time.asctime() converts the time tuple to a human-readable string.

Python time.strftime() Function

The strftime() function takes struct_time (or tuple corresponding to it) as an argument and returns a string representing it based on the format code used. For example,

import time named_tuple = time.localtime() # get struct_time time_string = time.strftime("%m/%d/%Y, %H:%M:%S", named_tuple) print(time_string)

Here, %Y , %m , %d , %H etc. are format codes.

  • %Y - year [0001. 2018, 2019. 9999]
  • %m - month [01, 02, . 11, 12]
  • %d - day [01, 02, . 30, 31]
  • %H - hour [00, 01, . 22, 23
  • %M - minutes [00, 01, . 58, 59]
  • %S - second [00, 01, . 58, 61]

Python time.strptime() Function

The strptime() function parses a string representing time and returns struct_time .

import time time_string = "14 July, 2023" result = time.strptime(time_string, "%d %B, %Y") print(result)
time.struct_time(tm_year=2023, tm_mon=7, tm_mday=14, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=-1)

Here, strptime() parses a string and convert it to the struct_time object.

Table of Contents

Источник

Оцените статью