datetime — Базові типи дати і часу — Python 3.15.2 documentation
Навігація індекс модулі | наступний | попередній | Python » 3.15.2 documentation » The Python standard library » Типи даних » datetime — Базові типи дати і часу | Theme | datetime — Базові типи дати і часу ¶ Вихідний код: Lib/datetime.py Модуль datetime постачає класи для маніпуляції датою і часом.
Хоча арифметика дати й часу підтримується, основна увага при реалізації зосереджена на ефективному отриманні атрибутів для форматування виводу та обробки. Порада Пропустити до кодів формату . Дивись також Модуль calendar Загальні функції, пов’язані з календарем.
Модуль time Доступ до часу та перетворення. Модуль zoneinfo Конкретні часові пояси, що представляють базу часових поясів IANA. Пакет dateutil Бібліотека третьої сторони з розширеним часовим поясом і підтримкою аналізу. Пакет DateType Third-party library that introduces distinct static types to for example, allow static type checkers to differentiate between naive and aware datetimes.
Aware and naive objects ¶ Date and time objects may be categorized as «aware» or «naive» depending on whether or not they include time zone information. Завдяки достатнім знанням застосовних алгоритмів і політичних коригувань часу, таких як інформація про часовий пояс і літній час, свідомий об’єкт може визначити своє місцезнаходження відносно інших обізнаних об’єктів.
Усвідомлюваний об’єкт представляє конкретний момент часу, який не піддається інтерпретації. [ 1 ] A naive object does not contain enough information to unambiguously locate itself relative to other date/time objects. Whether a naive object represents Coordinated Universal Time (UTC), local time, or time in some other time zone is purely up to the program, just like it is up to the program whether a particular number represents metres, miles, or mass.
Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of reality. For applications requiring aware objects, datetime and time objects have an optional time zone information attribute, tzinfo , that can be set to an instance of a subclass of the abstract tzinfo class. These tzinfo objects capture information about the offset from UTC time, the time zone name, and whether daylight saving time is in effect.
Only one concrete tzinfo class, the timezone class, is supplied by the datetime module. The timezone class can represent simple time zones with fixed offsets from UTC, such as UTC itself or North American EST and EDT time zones. Supporting time zones at deeper levels of detail is up to the application. The rules for time adjustment across the world are more political than rational, change frequently, and there is no standard suitable for every application aside from UTC.
Константи ¶ The datetime module exports the following constants: datetime. MINYEAR ¶ The smallest year number allowed in a date or datetime object. MINYEAR is 1. datetime. MAXYEAR ¶ The largest year number allowed in a date or datetime object. MAXYEAR is 9999. datetime. UTC ¶ Alias for the UTC time zone singleton datetime.timezone.utc . Added in version 3.11. Available types ¶ class datetime. date Ідеалізована наївна дата, припускаючи, що поточний григоріанський календар завжди був і завжди буде в силі.
Атрибути: year , month і day . class datetime. time Ідеалізований час, незалежний від будь-якого конкретного дня, припускаючи, що кожен день має рівно 24*60*60 секунд. (Тут немає поняття «високосні секунди».) Атрибути: hour , minute , second , microsecond і tzinfo . class datetime. datetime Поєднання дати й часу.
Атрибути: year , month , day , hour , minute , second , microsecond і tzinfo . class datetime. timedelta A duration expressing the difference between two datetime or date instances to microsecond resolution. class datetime. tzinfo Абстрактний базовий клас для інформаційних об’єктів часового поясу. Вони використовуються класами datetime і time для надання настроюваного поняття коригування часу (наприклад, для врахування часового поясу та/або літнього часу). class datetime. timezone Клас, який реалізує tzinfo абстрактний базовий клас як фіксоване зміщення від UTC.
Added in version 3.2. Об’єкти цих типів незмінні. Subclass relationships: Common properties ¶ Типи date , datetime , time і timezone мають такі спільні риси: Об’єкти цих типів незмінні. Objects of these types are hashable , meaning that they can be used as dictionary keys. Об’єкти цих типів підтримують ефективне маринування за допомогою модуля pickle .
Determining if an object is aware or naive ¶ Об’єкти типу date завжди наївні. Об’єкт типу time або datetime може бути обізнаним або наївним. A datetime object d is aware if d.utcoffset() does not return None . Otherwise, d is naive. A time object t is aware if t.utcoffset() does not return None . Otherwise, t is naive. Розрізнення між обізнаним і наївним не стосується об’єктів timedelta . timedelta objects ¶ A timedelta object represents a duration, the difference between two datetime or date instances. class datetime. timedelta ( days = 0 , seconds = 0 , microseconds = 0 , milliseconds = 0 , minutes = 0 , hours = 0 , weeks = 0 ) ¶ All arguments are optional and default to 0.
Arguments may be integers or floats, and may be positive or negative. Усередині зберігаються лише дні , секунди та мікросекунди . Аргументи конвертуються в такі одиниці: Мілісекунда перетворюється на 1000 мікросекунд. Хвилина перетворюється на 60 секунд. Година перетворюється на 3600 секунд.
Тиждень перетворюється на 7 днів. і дні, секунди та мікросекунди потім нормалізуються, щоб представлення було унікальним, з 0 <= мікросекунди < 1000000 0 <= секунд < 3600*24 (кількість секунд в одному дні) -999999999 <= днів <= 999999999 У наступному прикладі показано, як будь-які аргументи, окрім днів , секунд і мікросекунд , «об’єднуються» та нормалізуються в ці три отримані атрибути: >>> import datetime as dt >>> delta = dt . timedelta ( ... days = 50 , ... seconds = 27 , ... microseconds = 10 , ... milliseconds = 29000 , ... minutes
The rest of this page is on the live site.