time — Time access and conversions¶
This module provides various time-related functions. For related functionality, see also the datetime and calendar modules.
Although this module is always available, not all functions are available on all platforms. Most of the functions defined in this module call platform C library functions with the same name. It may sometimes be helpful to consult the platform documentation, because the semantics of these functions varies among platforms.
An explanation of some terminology and conventions is in order.
The epoch is the point where the time starts, the return value of time.gmtime(0) . It is January 1, 1970, 00:00:00 (UTC) on all platforms.
The term seconds since the epoch refers to the total number of elapsed seconds since the epoch, typically excluding leap seconds. Leap seconds are excluded from this total on all POSIX-compliant platforms.
The functions in this module may not handle dates and times before the epoch or far in the future. The cut-off point in the future is determined by the C library; for 32-bit systems, it is typically in 2038.
Function strptime() can parse 2-digit years when given %y format code. When 2-digit years are parsed, they are converted according to the POSIX and ISO C standards: values 69–99 are mapped to 1969–1999, and values 0–68 are mapped to 2000–2068.
UTC is Coordinated Universal Time (formerly known as Greenwich Mean Time, or GMT). The acronym UTC is not a mistake but a compromise between English and French.
DST is Daylight Saving Time, an adjustment of the timezone by (usually) one hour during part of the year. DST rules are magic (determined by local law) and can change from year to year. The C library has a table containing the local rules (often it is read from a system file for flexibility) and is the only source of True Wisdom in this respect.
The precision of the various real-time functions may be less than suggested by the units in which their value or argument is expressed. E.g. on most Unix systems, the clock “ticks” only 50 or 100 times a second.
On the other hand, the precision of time() and sleep() is better than their Unix equivalents: times are expressed as floating point numbers, time() returns the most accurate time available (using Unix gettimeofday() where available), and sleep() will accept a time with a nonzero fraction (Unix select() is used to implement this, where available).
The time value as returned by gmtime() , localtime() , and strptime() , and accepted by asctime() , mktime() and strftime() , is a sequence of 9 integers. The return values of gmtime() , localtime() , and strptime() also offer attribute names for individual fields.
See struct_time for a description of these objects.
Changed in version 3.3: The struct_time type was extended to provide the tm_gmtoff and tm_zone attributes when platform supports corresponding struct tm members.
Changed in version 3.6: The struct_time attributes tm_gmtoff and tm_zone are now available on all platforms.
Use the following functions to convert between time representations:
seconds since the epoch
seconds since the epoch
seconds since the epoch
seconds since the epoch
Functions¶
Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string of the following form: ‘Sun Jun 20 23:21:05 1993’ . The day field is two characters long and is space padded if the day is a single digit, e.g.: ‘Wed Jun 9 04:26:40 1993’ .
If t is not provided, the current time as returned by localtime() is used. Locale information is not used by asctime() .
Unlike the C function of the same name, asctime() does not add a trailing newline.
Return the clk_id of the thread-specific CPU-time clock for the specified thread_id.
Use threading.get_ident() or the ident attribute of threading.Thread objects to get a suitable value for thread_id.
Passing an invalid or expired thread_id may result in undefined behavior, such as segmentation fault.
See the man page for pthread_getcpuclockid(3) for further information.
New in version 3.7.
Return the resolution (precision) of the specified clock clk_id. Refer to Clock ID Constants for a list of accepted values for clk_id.
New in version 3.3.
Return the time of the specified clock clk_id. Refer to Clock ID Constants for a list of accepted values for clk_id.
Use clock_gettime_ns() to avoid the precision loss caused by the float type.
New in version 3.3.
Similar to clock_gettime() but return time as nanoseconds.
New in version 3.7.
Set the time of the specified clock clk_id. Currently, CLOCK_REALTIME is the only accepted value for clk_id.
Use clock_settime_ns() to avoid the precision loss caused by the float type.
New in version 3.3.
Similar to clock_settime() but set time with nanoseconds.
New in version 3.7.
Convert a time expressed in seconds since the epoch to a string of a form: ‘Sun Jun 20 23:21:05 1993’ representing local time. The day field is two characters long and is space padded if the day is a single digit, e.g.: ‘Wed Jun 9 04:26:40 1993’ .
If secs is not provided or None , the current time as returned by time() is used. ctime(secs) is equivalent to asctime(localtime(secs)) . Locale information is not used by ctime() .
time. get_clock_info ( name ) ¶
Get information on the specified clock as a namespace object. Supported clock names and the corresponding functions to read their value are:
The result has the following attributes:
adjustable: True if the clock can be changed automatically (e.g. by a NTP daemon) or manually by the system administrator, False otherwise
implementation: The name of the underlying C function used to get the clock value. Refer to Clock ID Constants for possible values.
monotonic: True if the clock cannot go backward, False otherwise
resolution: The resolution of the clock in seconds ( float )
New in version 3.3.
Convert a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero. If secs is not provided or None , the current time as returned by time() is used. Fractions of a second are ignored. See above for a description of the struct_time object. See calendar.timegm() for the inverse of this function.
time. localtime ( [ secs ] ) ¶
Like gmtime() but converts to local time. If secs is not provided or None , the current time as returned by time() is used. The dst flag is set to 1 when DST applies to the given time.
localtime() may raise OverflowError , if the timestamp is outside the range of values supported by the platform C localtime() or gmtime() functions, and OSError on localtime() or gmtime() failure. It’s common for this to be restricted to years between 1970 and 2038.
This is the inverse function of localtime() . Its argument is the struct_time or full 9-tuple (since the dst flag is needed; use -1 as the dst flag if it is unknown) which expresses the time in local time, not UTC. It returns a floating point number, for compatibility with time() . If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised (which depends on whether the invalid value is caught by Python or the underlying C libraries). The earliest date for which it can generate a time is platform-dependent.
Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.
Use monotonic_ns() to avoid the precision loss caused by the float type.
New in version 3.3.
Changed in version 3.5: The function is now always available and always system-wide.
Changed in version 3.10: On macOS, the function is now system-wide.
Similar to monotonic() , but return time as nanoseconds.
New in version 3.7.
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.
Use perf_counter_ns() to avoid the precision loss caused by the float type.
New in version 3.3.
Changed in version 3.10: On Windows, the function is now system-wide.
Similar to perf_counter() , but return time as nanoseconds.
New in version 3.7.
Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. It is process-wide by definition. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.
Use process_time_ns() to avoid the precision loss caused by the float type.
New in version 3.3.
Similar to process_time() but return time as nanoseconds.
New in version 3.7.
Suspend execution of the calling thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time.
If the sleep is interrupted by a signal and no exception is raised by the signal handler, the sleep is restarted with a recomputed timeout.
The suspension time may be longer than requested by an arbitrary amount, because of the scheduling of other activity in the system.
On Windows, if secs is zero, the thread relinquishes the remainder of its time slice to any other thread that is ready to run. If there are no other threads ready to run, the function returns immediately, and the thread continues execution. On Windows 8.1 and newer the implementation uses a high-resolution timer which provides resolution of 100 nanoseconds. If secs is zero, Sleep(0) is used.
Use clock_nanosleep() if available (resolution: 1 nanosecond);
Or use nanosleep() if available (resolution: 1 nanosecond);
Or use select() (resolution: 1 microsecond).
Changed in version 3.11: On Unix, the clock_nanosleep() and nanosleep() functions are now used if available. On Windows, a waitable timer is now used.
Changed in version 3.5: The function now sleeps at least secs even if the sleep is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale).
Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument. If t is not provided, the current time as returned by localtime() is used. format must be a string. ValueError is raised if any field in t is outside of the allowed range.
0 is a legal argument for any position in the time tuple; if it is normally illegal the value is forced to a correct one.
The following directives can be embedded in the format string. They are shown without the optional field width and precision specification, and are replaced by the indicated characters in the strftime() result:
# Работа со временем
Для работы со временем в Python импортируют библиотеку datetime (англ. date «дата», time «время»). В ней есть не только отдельные функции, но и целый новый тип данных.
Называется он точно так же, как библиотека — datetime . Чтобы не путаться, будем подключать библиотеку под именем dt и так всегда к ней обращаться.
Тип данных datetime похож на уже привычные вам int , string и dict . Он нужен, чтобы хранить информацию о конкретном моменте времени: год, месяц, день, час, минуты, секунды и микросекунды.
Чтобы создать объект этого типа, нужно вызвать функцию datetime() из библиотеки dt . Она принимает обязательные аргументы — год, месяц и день, — и необязательные: час, минута, секунда и микросекунда, которые по умолчанию равны нулю.
Создадим объект типа datetime с датой и временем старта Гагарина:
Тип данных datetime позволяет просто вычитать даты друг из друга, как обычные числа. Вот время между стартом Гагарина и его приземлением:
# Упражнения
- Научите Виту сообщать пользователю, сколько времени шёл его любимый сериал.
- Дата выхода первой серии — 17 апреля 2011 года.
- Дата выхода последней серии — 15 апреля 2019 года.
- Напишите код, отвечающий на запрос пользователя "Сколько времени у меня уже ушло на этот курс по разработке?" Вспомните, в какой день и во сколько вы начали проходить курс. Запишите этот момент времени в переменную start_moment . В переменную current_moment запишите текущий момент времени. Затем вычислите разницу двух этих моментов, запишите её в переменную total_time , и напечатайте её на экране.
# Стандарт UTC
Есть несколько стандартов измерения и записи времени. Раньше в основном придерживались GMT (англ. «Greenwich Mean Time», среднее время по гринвичскому меридиану). Позже прежний всемирный формат был отменен и приняли новый, определяемый атомными часами. Это UTC — «coordinated universal time» — всемирное координированное время.
У каждой переменной типа данных datetime можно вызвать метод utcnow() (англ. now «сейчас»). Он вернёт текущий момент времени по UTC с эталонной точностью до микросекунд.
Более того, метод utcnow() настолько хитрый, что для его вызова необязательно явно создавать объект типа datetime . Можно просто написать:
Для получения времени другого часового пояса, есть тип timedelta (от англ. delta, «промежуток»), в котором можно сохранить определенный промежуток времени. Этот тип тоже живёт в библиотеке dt. А объект такого типа создаётся функцией timedelta() :
И прибавляем его к значению времени по UTC:
В аргументах функции timedelta() среди прочего можно указывать days (дни), hours (часы), minutes (минуты), seconds (секунды), microseconds (микросекунды).
Пример: Победитель Гран-при Австралии чемпионата мира Формулы-1 2019 года, Вале Боттас проехал свой самый быстрый круг за 1 минуту 25 секунд и 273250 микросекунд. Второй результат показал Льюис Хэмилтон с разницей в 208860 микросекунд. Вычислим время самого быстрого круга Хэмилтона.
# Упражнения
- Напишите функцию, которая по названию города скажет, сколько там сейчас времени. В словарь UTC_OFFSET (англ. offset, «сдвиг»), для каждого города записана разница местного времени и UTC в часах.
Подключите метод перебора и выведите фразу для каждого города: "В Уфе 5 часов." Используйте проверку для правильно подобранного окончания слова "часы" в зависимости от числа.
Напишите функцию, которая по имени друга скажет, сколько у него сейчас времени. В словаре DATABASE хранятся данные о том, кто из друзей где живёт.
- Подключите метод перебора друзей и выведите фразу для каждого друга: "У Димы сейчас 15 часов." Используйте проверку для правильно подобранного окончания слова "часы" в зависимости от числа.
# Форматирование времени
До сих пор вы печатали время только в одном формате.
Что делать, если хочется напечатать сообщение по-человечески, скажем: "Сейчас 10:31"? Для этого существует метод strftime() (от англ. string format time, «строковый формат времени»). Его можно применить к любому объекту типа datetime и аргументом задать формат вывода времени:
Здесь %H означает часы, %M — минуты. Кроме этих параметров, бывают ещё, например %B — месяц, %Y — год и %S — секунды, %A — название дня недели по-английски, %U — номер недели в году.
# Упражнения
- Сделайте так, чтобы функция what_time() возвращала время в формате часы:минуты .
- Примените все полученные в этой теме знания, чтобы научить Виту отвечать на вопросы про друзей, сколько у них сейчас времени:
- Артём, который час?
- Антон, который час?
Примеры таких запросов уже добавлены в список queries в функции runner() .
Текущая дата и время в Python
Время и дата играют важнейшую роль при решении определенных задач в программировании. Разработчику на Python приходится нередко использовать точные значения текущей (current) даты, к примеру, при сохранении информации в базе данных, вычислениях, регистрации, обеспечении доступа и т. д. В этой статье пойдет разговор о том, как узнать текущие временные значения с помощью модуля datetime. Вдобавок к этому, читатель узнает о временных настройках для разных часовых поясов и преобразовании объектов datetime в метки времени Unix.
Получаем текущую дату и время
Datetime включает в себя разные классы, позволяющие получать нужные временные данные:
- datetime.date: день, месяц и год;
- datetime.time: время в часах, минутах, секундах, а также микросекундах. Тут дата значения не имеет;
- datetime.datetime: здесь хранятся атрибуты date и time.
Для примера можно вывести в терминал текущую (current) дату и время. Можно воспользоваться объектом datetime.datetime — из него довольно просто извлекаются объекты date и time. Сначала следует импортировать требуемый модуль:
from datetime import datetime
Да, это выглядит странновато, т. к. речь идет о получении класса datetime из модуля datetime, однако это 2 разные вещи. Далее следует воспользоваться функцией now() — она позволит получить объект с текущим временем и датой.
from datetime import datetime
Набрав код выше, вы увидите на экране следующее (в вашем случае вывод изменится, ведь минуты не стоят на месте):

Что произошло? Функция now() отобразила объект, причем с датой и временем создания этого самого объекта. В результате была выведена соответствующая строка. Однако никто не мешает получить временные атрибуты отдельно:

Таким образом, метод now() вполне годится для получения текущей даты и времени. Но что делать, если надо получить лишь дату?
Работа с датой current
Существуют 2 способа получения текущей даты. Первый выводит нужные данные из объекта datetime посредством метода date() :

Во втором применяется метод today() класса date:

Класс datetime.date позволяет получать календарную дату. Также следует добавить, что его атрибуты (year, month, day) бывают доступны и отдельно, как в примере с datetime.

Тут все понятно и просто. Но есть нюанс: если надо получить день недели, прописывают current_date.weekday()+1 . Дело в том, что нумерация дней недели начинается с нуля, то есть понедельник — это 0, вторник — 1, среда — 2 и так далее. Если такое положение вещей устраивает, +1 можно и не добавлять.
А как поступить, если надо отобразить текущее время отдельно от даты?
Работаем с текущим временем
Текущее время от объекта datetime получают посредством метода time() . Вот как это выглядит:

Здесь отдельно получить часы, минуты, секунды и микросекунды не представляется возможным, да в этом и нет необходимости, т. к. само понятие времени суток не предполагает другого отображения.
Важно отметить, что есть возможность получить временные данные и с учетом нужного часового пояса (timezone). Как и что используется, поговорим ниже.
Другой часовой пояс: временные зоны (timezones)
Метод now() принимает в Python временную зону в качестве аргумента, так что объект datetime генерируется соответствующим образом.
Для получения информации с учетом часового пояса необходимо задействовать библиотеку pytz (если ее нет, потребуется инсталляция, для чего подойдет команда pip3 install pytz ).
Так как я нахожусь в Минске, давайте получим текущие временные значения (times) именно для Минска:

Строка в коде minsk_current_datetime является объектом datetime, то есть все то же самое, что и ранее, но уже в полном соответствии с часовым поясом Республики Беларусь.
Когда надо узнать время в UTC, тоже пригодится модуль pytz:

Получить время UTC можно и без модуля pytz, т. к. datetime имеет полезное свойство timezone. Что же, давайте задействуем свойство timezone:

Таким образом, можно без проблем преобразовать текущие даты и значения времени в различные часовые пояса.
Преобразование временных меток
Также может быть очень полезным преобразовывать время в один из самых широко применяемых форматов в вычислениях. Речь идет о временных метках Unix.
Доподлинно известно, что компьютерные системы измеряют время не так, как люди. Здесь за основу берется число секунд, которые прошли с начала Unix-эпохи, то есть с 00:00:00 UTC 1.01.1979. Базы данных, протоколы и приложения обычно задействуют временную метку.
Для ее получения в «Питоне» пригодится модуль time, следовательно, первая строка будет import time :

Функция time.time() возвращает пользователю число с плавающей запятой и с временной меткой Unix.
На этом все. Очень надеемся, что вы получили некоторое представление об использовании встроенных Python-библиотек и модулей, необходимых для отображения временных значений.
How do I get the current time?
![]()
To save typing, you can import the datetime object from the datetime module:
Then remove the prefix datetime. from all of the above.
![]()
![]()
Example output: ‘2013-09-18 11:16:32’
![]()
![]()
Similar to Harley’s answer, but use the str() function for a quick-n-dirty, slightly more human readable format:
How do I get the current time in Python?
The time module
The time module provides functions that tell us the time in "seconds since the epoch" as well as other utilities.
Unix Epoch Time
This is the format you should get timestamps in for saving in databases. It is a simple floating-point number that can be converted to an integer. It is also good for arithmetic in seconds, as it represents the number of seconds since Jan 1, 1970, 00:00:00, and it is memory light relative to the other representations of time we’ll be looking at next:
This timestamp does not account for leap-seconds, so it’s not linear — leap seconds are ignored. So while it is not equivalent to the international UTC standard, it is close, and therefore quite good for most cases of record-keeping.
This is not ideal for human scheduling, however. If you have a future event you wish to take place at a certain point in time, you’ll want to store that time with a string that can be parsed into a datetime object or a serialized datetime object (these will be described later).
time.ctime
You can also represent the current time in the way preferred by your operating system (which means it can change when you change your system preferences, so don’t rely on this to be standard across all systems, as I’ve seen others expect). This is typically user friendly, but doesn’t typically result in strings one can sort chronologically:
You can hydrate timestamps into human readable form with ctime as well:
This conversion is also not good for record-keeping (except in text that will only be parsed by humans — and with improved Optical Character Recognition and Artificial Intelligence, I think the number of these cases will diminish).
datetime module
The datetime module is also quite useful here:
datetime.datetime.now
The datetime.now is a class method that returns the current time. It uses the time.localtime without the timezone info (if not given, otherwise see timezone aware below). It has a representation (which would allow you to recreate an equivalent object) echoed on the shell, but when printed (or coerced to a str ), it is in human readable (and nearly ISO) format, and the lexicographic sort is equivalent to the chronological sort:
datetime’s utcnow
You can get a datetime object in UTC time, a global standard, by doing this:
UTC is a time standard that is nearly equivalent to the GMT timezone. (While GMT and UTC do not change for Daylight Savings Time, their users may switch to other timezones, like British Summer Time, during the Summer.)
datetime timezone aware
However, none of the datetime objects we’ve created so far can be easily converted to various timezones. We can solve that problem with the pytz module:
Equivalently, in Python 3 we have the timezone class with a utc timezone instance attached, which also makes the object timezone aware (but to convert to another timezone without the handy pytz module is left as an exercise to the reader):
And we see we can easily convert to timezones from the original UTC object.
You can also make a naive datetime object aware with the pytz timezone localize method, or by replacing the tzinfo attribute (with replace , this is done blindly), but these are more last resorts than best practices:
The pytz module allows us to make our datetime objects timezone aware and convert the times to the hundreds of timezones available in the pytz module.
One could ostensibly serialize this object for UTC time and store that in a database, but it would require far more memory and be more prone to error than simply storing the Unix Epoch time, which I demonstrated first.
The other ways of viewing times are much more error-prone, especially when dealing with data that may come from different time zones. You want there to be no confusion as to which timezone a string or serialized datetime object was intended for.
If you’re displaying the time with Python for the user, ctime works nicely, not in a table (it doesn’t typically sort well), but perhaps in a clock. However, I personally recommend, when dealing with time in Python, either using Unix time, or a timezone aware UTC datetime object.