Работа с датой и временем в python

struct_time¶

Storing times as elapsed seconds is useful in some situations, but
there are times when you need to have access to the individual fields
of a date (year, month, etc.). The module defines
struct_time for holding date and time values with components
broken out so they are easy to access. There are several functions
that work with struct_time values instead of floats.

import time

print 'gmtime   :', time.gmtime()
print 'localtime:', time.localtime()
print 'mktime   :', time.mktime(time.localtime())

print
t = time.localtime()
print 'Day of month:', t.tm_mday
print ' Day of week:', t.tm_wday
print ' Day of year:', t.tm_yday

gmtime() returns the current time in UTC. localtime()
returns the current time with the current time zone
applied. mktime() takes a struct_time and converts it
to the floating point representation.

Wall Clock Time¶

One of the core functions of the module is ,
which returns the number of seconds since the start of the epoch as a
floating point value.

import time

print 'The time is:', time.time()

Although the value is always a float, actual precision is
platform-dependent.

$ python time_time.py
The time is: 1205079300.54

The float representation is useful when storing or comparing dates,
but not as useful for producing human readable representations. For
logging or printing time ctime() can be more useful.

import time

print 'The time is      :', time.ctime()
later = time.time() + 15
print '15 secs from now :', time.ctime(later)

Here the second output line shows how to use ctime() to format
a time value other than the current time.

Working with Time Zones¶

The functions for determining the current time depend on having the time zone
set, either by your program or by using a default time zone set for the
system. Changing the time zone does not change the actual time, just the way
it is represented.

To change the time zone, set the environment variable TZ, then
call tzset(). Using TZ, you can specify the time zone with a
lot of detail, right down to the start and stop times for daylight
savings time. It is usually easier to use the time zone name and let
the underlying libraries derive the other information, though.

This example program changes the time zone to a few different values
and shows how the changes affect other settings in the time module.

import time
import os

def show_zone_info():
    print '\tTZ    :', os.environ.get('TZ', '(not set)')
    print '\ttzname:', time.tzname
    print '\tZone  : %d (%d)' % (time.timezone, (time.timezone  3600))
    print '\tDST   :', time.daylight
    print '\tTime  :', time.ctime()
    print

print 'Default :'
show_zone_info()

for zone in  'US/Eastern', 'US/Pacific', 'GMT', 'Europe/Amsterdam' ]:
    os.environ'TZ' = zone
    time.tzset()
    print zone, ':'
    show_zone_info()

My default time zone is US/Eastern, so setting TZ to that has no
effect. The other zones used change the tzname, daylight flag, and
timezone offset value.

$ python time_timezone.py
Default :
    TZ    : (not set)
    tzname: ('EST', 'EDT')
    Zone  : 18000 (5)
    DST   : 1
    Time  : Sun Mar  9 13:06:53 2008

US/Eastern :
    TZ    : US/Eastern
    tzname: ('EST', 'EDT')
    Zone  : 18000 (5)
    DST   : 1
    Time  : Sun Mar  9 13:06:53 2008

US/Pacific :
    TZ    : US/Pacific
    tzname: ('PST', 'PDT')
    Zone  : 28800 (8)
    DST   : 1
    Time  : Sun Mar  9 10:06:53 2008

GMT :
    TZ    : GMT
    tzname: ('GMT', 'GMT')
    Zone  : 0 (0)
    DST   : 0
    Time  : Sun Mar  9 17:06:53 2008

Europe/Amsterdam :
    TZ    : Europe/Amsterdam
    tzname: ('CET', 'CEST')
    Zone  : -3600 (-1)
    DST   : 1
    Time  : Sun Mar  9 18:06:53 2008

See also

time
Standard library documentation for this module.
The datetime module includes other classes for doing calculations with dates and times.
Work with higher-level date functions to produce calendars or
calculate recurring events.

Parsing and Formatting Times¶

The two functions strptime() and strftime() convert
between struct_time and string representations of time values. There
is a long list of formatting instructions available to support input
and output in different styles. The complete list is documented in the
library documentation for the time module.

This example converts the current time from a string, to a
struct_time instance, and back to a string.

import time

now = time.ctime()
print now
parsed = time.strptime(now)
print parsed
print time.strftime("%a %b %d %H:%M:%S %Y", parsed)

The output string is not exactly like the input, since the day of the
month is prefixed with a zero.

COPYRIGHT top

       Portions of this text are reprinted and reproduced in electronic form
       from IEEE Std 1003.1, 2013 Edition, Standard for Information
       Technology -- Portable Operating System Interface (POSIX), The Open
       Group Base Specifications Issue 7, Copyright (C) 2013 by the
       Institute of Electrical and Electronics Engineers, Inc and The Open
       Group.  (This is POSIX.1-2008 with the 2013 Technical Corrigendum 1
       applied.) In the event of any discrepancy between this version and
       the original IEEE and The Open Group Standard, the original IEEE and
       The Open Group Standard is the referee document. The original
       Standard can be obtained online at http://www.unix.org/online.html .

       Any typographical or formatting errors that appear in this page are
       most likely to have been introduced during the conversion of the
       source files to man page format. To report such errors, see
       https://www.kernel.org/doc/man-pages/reporting_bugs.html .

IEEE/The Open Group                 2013                          GMTIME(3P)

Pages that refer to this page:
time.h(0p), 
asctime(3p), 
asctime_r(3p), 
clock(3p), 
ctime(3p), 
ctime_r(3p), 
difftime(3p), 
localtime(3p), 
localtime_r(3p), 
mktime(3p), 
strftime(3p), 
strftime_l(3p), 
time(3p)

Возвращаемое значениеReturn Value

Указатель на структуру типа tm.A pointer to a structure of type tm. Поля возвращаемой структуры содержат вычисленное значение аргумента саурцетиме в формате UTC, а не в местном времени.The fields of the returned structure hold the evaluated value of the sourceTime argument in UTC rather than in local time. Каждое из полей структуры имеет тип , как показано ниже.Each of the structure fields is of type , as follows:

ПолеField Описание:Description
tm_sectm_sec Секунд после минуты (0-59).Seconds after minute (0 — 59).
tm_mintm_min Минут после часа (0-59).Minutes after hour (0 — 59).
tm_hourtm_hour Часы с полуночи (0-23).Hours since midnight (0 — 23).
tm_mdaytm_mday День месяца (1-31).Day of month (1 — 31).
tm_montm_mon Месяц (0-11; Январь = 0).Month (0 — 11; January = 0).
tm_yeartm_year Год (текущий год минус 1900).Year (current year minus 1900).
tm_wdaytm_wday День недели (0-6; Воскресенье = 0).Day of week (0 — 6; Sunday = 0).
tm_ydaytm_yday День года (0-365; 1 января = 0).Day of year (0 — 365; January 1 = 0).
tm_isdsttm_isdst Значение всегда равно 0 для gmtime.Always 0 for gmtime.

И 32-разрядные, и 64-разрядные версии gmtime, функциях mktime, мкгмтимеи localtime используют одну общую структуру TM для каждого потока для преобразования.Both the 32-bit and 64-bit versions of gmtime, mktime, mkgmtime, and localtime all use one common tm structure per thread for the conversion. Каждый вызов одной из этих функций уничтожает результат любого предыдущего вызова.Each call to one of these functions destroys the result of any previous call. Если саурцетиме представляет дату до полуночи 1 января 1970 г., gmtime возвращает значение NULL.If sourceTime represents a date before midnight, January 1, 1970, gmtime returns NULL. Ошибка не возвращается.There is no error return.

_gmtime64, в котором используется структура __time64_t , позволяет выражать даты до 23:59:59, 31 декабря 3000, в формате utc, тогда как _gmtime32 представляют даты только до 23:59:59 18 января 2038 года, UTC._gmtime64, which uses the __time64_t structure, enables dates to be expressed up through 23:59:59, December 31, 3000, UTC, whereas _gmtime32 only represent dates through 23:59:59 January 18, 2038, UTC. Полночь 1-ого января 1970 года — нижняя граница диапазона дат для обеих функций.Midnight, January 1, 1970, is the lower bound of the date range for both functions.

gmtime — это встроенная функция, которая возвращает _gmtime64, а time_t эквивалентна __time64_t , если не определен _USE_32BIT_TIME_T .gmtime is an inline function that evaluates to _gmtime64, and time_t is equivalent to __time64_t unless _USE_32BIT_TIME_T is defined. Если необходимо заставить компилятор интерпретировать time_t как старый 32-разрядный time_t, можно определить _USE_32BIT_TIME_T, но это приведет к тому, что gmtime будет встроен в _gmtime32 и time_t быть определен как __time32_t.If you must force the compiler to interpret time_t as the old 32-bit time_t, you can define _USE_32BIT_TIME_T, but doing so causes gmtime to be in-lined to _gmtime32 and time_t to be defined as __time32_t. Рекомендуется не делать этого, поскольку данная возможность не поддерживается на 64-разрядных платформах и, в любом случае, ваше приложение может завершиться с ошибкой после 18-го января 2038 года.We recommend that you do not do this, because it is not allowed on 64-bit platforms and in any case your application may fail after January 18, 2038.

Эти функции проверяют свои параметры.These functions validate their parameters. Если саурцетиме является пустым указателем или значение саурцетиме является отрицательным, эти функции вызывают обработчик недопустимого параметра, как описано в разделе Проверка параметров.If sourceTime is a null pointer, or if the sourceTime value is negative, these functions invoke an invalid parameter handler, as described in Parameter Validation. Если выполнение может быть продолжено, функции возвращают значение NULL и задают значение еинвал.If execution is allowed to continue, the functions return NULL and set errno to EINVAL.

RemarksRemarks

Функции _mkgmtime32 и _mkgmtime64 преобразуют время в формате UTC в тип __time32_t или __time64_t , представляющий время в формате UTC.The _mkgmtime32 and _mkgmtime64 functions convert a UTC time to a __time32_t or __time64_t type representing the time in UTC. Чтобы преобразовать местное время в время в формате UTC, используйте вместо него функциях mktime, _mktime32и _mktime64 .To convert a local time to UTC time, use mktime, _mktime32, and _mktime64 instead.

_mkgmtime является встроенной функцией, результатом которой является _mkgmtime64, а time_t эквивалентна __time64_t._mkgmtime is an inline function that evaluates to _mkgmtime64, and time_t is equivalent to __time64_t. Если необходимо заставить компилятор интерпретировать time_t как старый 32-разрядный time_t, можно определить _USE_32BIT_TIME_T.If you need to force the compiler to interpret time_t as the old 32-bit time_t, you can define _USE_32BIT_TIME_T. Это не рекомендуется, так как приложение может завершиться сбоем после 18 января 2038, максимального диапазона 32-разрядной time_t.We don’t recommend it, because your application might fail after January 18, 2038, the maximum range of a 32-bit time_t. На 64-разрядных платформах это не разрешено.It’s not allowed at all on 64-bit platforms.

Переданная структура времени изменяется следующим образом, так же как и _mktime функции: поля tm_wday и tm_yday устанавливаются в новые значения на основе значений tm_mday и tm_year.The time structure passed in is changed as follows, in the same way as it’s changed by the _mktime functions: the tm_wday and tm_yday fields are set to new values based on the values of tm_mday and tm_year. Так как время предполагается в формате UTC, поле tm_isdst игнорируется.Because the time is assumed to be UTC, the tm_isdst field is ignored.

Диапазон функций _mkgmtime32 — от полуночи 1 января 1970 г., utc — 23:59:59 18, 2038, UTC.The range of the _mkgmtime32 function is from midnight, January 1, 1970, UTC to 23:59:59 January 18, 2038, UTC. Диапазон _mkgmtime64 — от полуночи 1 января 1970 г., время в формате utc до 23:59:59, 31 декабря 3000, UTC.The range of _mkgmtime64 is from midnight, January 1, 1970, UTC to 23:59:59, December 31, 3000, UTC. Дата вне диапазона приводит к возвращению значения-1.An out-of-range date results in a return value of -1. Диапазон _mkgmtime зависит от того, определен ли _USE_32BIT_TIME_T .The range of _mkgmtime depends on whether _USE_32BIT_TIME_T is defined. Если она не определена по умолчанию, то диапазон будет таким же, как и _mkgmtime64.When it’s not defined, which is the default, the range is the same as _mkgmtime64. В противном случае диапазон ограничен 32-разрядным диапазоном _mkgmtime32.Otherwise, the range is limited to the 32-bit range of _mkgmtime32.

Как gmtime , так и localtime используют общий статический буфер для преобразования.Both gmtime and localtime use a common static buffer for the conversion. Если указать этот буфер для _mkgmtime, предыдущее содержимое уничтожается.If you supply this buffer to _mkgmtime, the previous contents are destroyed.

По умолчанию глобальное состояние этой функции ограничивается приложением.By default, this function’s global state is scoped to the application. Чтобы изменить это, см. раздел глобальное состояние в CRT.To change this, see Global state in the CRT.

time.struct_time Class

Several functions in the module such as , etc. either take object as an argument or return it.

Here’s an example of object.

time.struct_time(tm_year=2018, tm_mon=12, tm_mday=27, 
                    tm_hour=6, tm_min=35, tm_sec=17, 
                    tm_wday=3, tm_yday=361, tm_isdst=0)
Index Attribute Values
0000, …., 2018, …, 9999
1 1, 2, …, 12
2 1, 2, …, 31
3 0, 1, …, 23
4 0, 1, …, 59
5 0, 1, …, 61
6 0, 1, …, 6; Monday is 0
7 1, 2, …, 366
8 0, 1 or -1

The values (elements) of the object are accessible using both indices and attributes.

Python time.localtime()

The function takes the number of seconds passed since epoch as an argument and returns in local time.

When you run the program, the output will be something like:

result: time.struct_time(tm_year=2018, tm_mon=12, tm_mday=27, tm_hour=15, tm_min=49, tm_sec=29, tm_wday=3, tm_yday=361, tm_isdst=0)

year: 2018
tm_hour: 15

If no argument or is passed to , the value returned by is used.

Python time.gmtime()

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

When you run the program, the output will be:

result = time.struct_time(tm_year=2018, tm_mon=12, tm_mday=28, tm_hour=8, tm_min=44, tm_sec=4, tm_wday=4, tm_yday=362, tm_isdst=0)

year = 2018
tm_hour = 8

If no argument or is passed to , the value returned by is used.

Python time.mktime()

The function takes (or a tuple containing 9 elements corresponding to ) as an argument and returns the seconds passed since epoch in local time. Basically, it’s the inverse function of .

The example below shows how and are related.

When you run the program, the output will be something like:

t1:  time.struct_time(tm_year=2018, tm_mon=12, tm_mday=27, tm_hour=15, tm_min=49, tm_sec=29, tm_wday=3, tm_yday=361, tm_isdst=0)

s: 1545925769.0

Python time.asctime()

The function takes (or a tuple containing 9 elements corresponding to ) as an argument and returns a string representing it. Here’s an example:

When you run the program, the output will be:

Result: Fri Dec 28 08:44:04 2018

Python time.strftime()

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

When you run the program, the output will be something like:

12/28/2018, 09:47:41

Here, , , , etc. are format codes.

  • — year
  • — month
  • — day
  • — hour [00, 01, …, 22, 23
  • — minutes 
  • — second

To learn more, visit: .

Python time.strptime()

The function parses a string representing time and returns .

When you run the program, the output will be:

time.struct_time(tm_year=2018, tm_mon=6, tm_mday=21, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=172, tm_isdst=-1)

RemarksRemarks

Функция _gmtime32 разбивает значение саурцетиме и сохраняет его в статической выделенной структуре типа TM, определенной во времени. Высоты.The _gmtime32 function breaks down the sourceTime value and stores it in a statically allocated structure of type tm, defined in TIME.H. Значение саурцетиме обычно получается из вызова функции времени .The value of sourceTime is typically obtained from a call to the time function.

Примечание

В большинстве случаев целевая среда пытается определить, действует ли летнее время.In most cases, the target environment tries to determine whether daylight savings time is in effect. Библиотека времени выполнения C принимает правила США для реализации проверки на летнее время (DST).The C run-time library assumes that the United States rules for implementing the calculation of Daylight Saving Time (DST) are used.

По умолчанию глобальное состояние этой функции ограничивается приложением.By default, this function’s global state is scoped to the application. Чтобы изменить это, см. раздел глобальное состояние в CRT.To change this, see Global state in the CRT.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *