datetime — Базові типи дати і часу¶
Вихідний код: Lib/datetime.py
Модуль datetime постачає класи для маніпуляції датою і часом.
Хоча арифметика дати й часу підтримується, основна увага при реалізації зосереджена на ефективному отриманні атрибутів для форматування виводу та обробки.
Порада
Пропустити до кодів формату.
Дивись також
- Модуль calendar
- Загальні функції, пов’язані з календарем. 
- Модуль time
- Доступ до часу та перетворення. 
- Модуль zoneinfo
- Конкретні часові пояси, що представляють базу часових поясів IANA. 
- Пакет dateutil
- Бібліотека третьої сторони з розширеним часовим поясом і підтримкою аналізу. 
- Пакет DateType
- Third-party library that introduces distinct static types to e.g. allow static type checkers to differentiate between naive and aware datetimes. 
Обізнані та наївні об’єкти¶
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.
Для додатків, яким потрібні об’єкти, об’єкти datetime і time мають необов’язковий атрибут інформації про часовий пояс, tzinfo, який можна встановити як екземпляр підкласу абстрактний tzinfo клас. Ці об’єкти tzinfo зберігають інформацію про зміщення від часу UTC, назву часового поясу та чи діє літній час.
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.UTC¶
- Alias for the UTC time zone singleton - datetime.timezone.utc.- Added in version 3.11. 
Доступні типи¶
- 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 - datetimeor- dateinstances to microsecond resolution.
- class datetime.tzinfo
- Абстрактний базовий клас для інформаційних об’єктів часового поясу. Вони використовуються класами - datetimeі- timeдля надання настроюваного поняття коригування часу (наприклад, для врахування часового поясу та/або літнього часу).
- class datetime.timezone
- Клас, який реалізує - tzinfoабстрактний базовий клас як фіксоване зміщення від UTC.- Added in version 3.2. 
Об’єкти цих типів незмінні.
Відносини підкласів:
object
    timedelta
    tzinfo
        timezone
    time
    date
        datetime
Загальні властивості¶
Типи date, datetime, time і timezone мають такі спільні риси:
Визначення того, чи є об’єкт усвідомленим чи наївним¶
Об’єкти типу date завжди наївні.
Об’єкт типу time або datetime може бути обізнаним або наївним.
A datetime object d is aware if both of the following hold:
- d.tzinfoне є- None
- d.tzinfo.utcoffset(d)не повертає- None
Otherwise, d is naive.
A time object t is aware if both of the following hold:
- t.tzinfoне є- None
- t.tzinfo.utcoffset(None)не повертає- None.
Otherwise, t is naive.
Розрізнення між обізнаним і наївним не стосується об’єктів timedelta.
timedelta Об’єкти¶
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
 - У наступному прикладі показано, як будь-які аргументи, окрім днів, секунд і мікросекунд, «об’єднуються» та нормалізуються в ці три отримані атрибути: - >>> from datetime import timedelta >>> delta = timedelta( ... days=50, ... seconds=27, ... microseconds=10, ... milliseconds=29000, ... minutes=5, ... hours=8, ... weeks=2 ... ) >>> # Only days, seconds, and microseconds remain >>> delta datetime.timedelta(days=64, seconds=29156, microseconds=10) - Якщо будь-який аргумент є числом із плаваючою точкою та є дробові мікросекунди, дробові мікросекунди, що залишилися від усіх аргументів, об’єднуються, а їхня сума округлюється до найближчої мікросекунди за допомогою тай-брейку округлення від половини до навіть. Якщо жоден аргумент не є числом з плаваючою речовиною, процеси перетворення та нормалізації є точними (інформація не втрачається). - Якщо нормалізоване значення днів лежить за межами зазначеного діапазону, виникає - OverflowError.- Зверніть увагу, що нормалізація від’ємних значень спочатку може викликати подив. Наприклад: - >>> from datetime import timedelta >>> d = timedelta(microseconds=-1) >>> (d.days, d.seconds, d.microseconds) (-1, 86399, 999999) - Since the string representation of - timedeltaobjects can be confusing, use the following recipe to produce a more readable format:- >>> def pretty_timedelta(td): ... if td.days >= 0: ... return str(td) ... return f'-({-td!s})' ... >>> d = timedelta(hours=-1) >>> str(d) # not human-friendly '-1 day, 23:00:00' >>> pretty_timedelta(d) '-(1:00:00)' 
Атрибути класу:
- timedelta.max¶
- Найбільш позитивний об’єкт - timedelta,- timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999).
- timedelta.resolution¶
- Найменша можлива різниця між нерівними об’єктами - timedelta,- timedelta(microseconds=1).
Note that, because of normalization, timedelta.max is greater than -timedelta.min.
-timedelta.max is not representable as a timedelta object.
Атрибути екземпляра (тільки для читання):
- timedelta.days¶
- Між -999,999,999 та 999,999,999 включно. 
- timedelta.seconds¶
- Між 0 та 86,399 включно. - Застереження - It is a somewhat common bug for code to unintentionally use this attribute when it is actually intended to get a - total_seconds()value instead:- >>> from datetime import timedelta >>> duration = timedelta(seconds=11235813) >>> duration.days, duration.seconds (130, 3813) >>> duration.total_seconds() 11235813.0 
- timedelta.microseconds¶
- Між 0 та 999,999 включно. 
Підтримувані операції:
| Операція | Результат | 
|---|---|
| 
 | Sum of  | 
| 
 | Difference of  | 
| 
 | Delta multiplied by an integer.
Afterwards  | 
| In general,  | |
| 
 | Дельта, помножена на float. Результат округлюється до найближчого кратного timedelta.resolution за допомогою округлення від половини до навіть. | 
| 
 | Division (3) of overall duration  | 
| 
 | Дельта, поділена на float або int. Результат округлюється до найближчого кратного timedelta.resolution за допомогою округлення від половини до навіть. | 
| 
 | Підлога обчислюється, а залишок (якщо є) викидається. У другому випадку повертається ціле число. (3) | 
| 
 | Залишок обчислюється як об’єкт  | 
| 
 | Computes the quotient and the remainder:
 | 
| 
 | Повертає об’єкт  | 
| 
 | Equivalent to  | 
| 
 | Equivalent to  | 
| 
 | Повертає рядок у формі  | 
| 
 | Повертає рядкове представлення об’єкта  | 
Примітки:
- Це точно, але може переповнюватись. 
- Це точно і не може переповнюватися. 
- Division by zero raises - ZeroDivisionError.
- -timedelta.maxis not representable as a- timedeltaobject.
- Рядкові представлення об’єктів - timedeltaнормалізуються подібно до їх внутрішнього представлення. Це призводить до дещо незвичайних результатів для негативних часових дельт. Наприклад:- >>> timedelta(hours=-5) datetime.timedelta(days=-1, seconds=68400) >>> print(_) -1 day, 19:00:00 
- Вираз - t2 - t3завжди дорівнюватиме виразу- t2 + (-t3), за винятком випадків, коли t3 дорівнює- timedelta.max; у цьому випадку перший дасть результат, а другий переповниться.
Окрім перерахованих вище операцій, об’єкти timedelta підтримують певні додавання та віднімання за допомогою об’єктів date і datetime (див. нижче).
Змінено в версії 3.2: Тепер підтримується поділ на поверх і справжній поділ об’єкта timedelta на інший об’єкт timedelta, а також операції з залишком і функція divmod(). Тепер підтримується справжнє ділення та множення об’єкта timedelta на об’єкт float.
timedelta objects support equality and order comparisons.
У логічних контекстах об’єкт timedelta вважається істинним тоді і тільки тоді, коли він не дорівнює timedelta(0).
Методи екземплярів:
- timedelta.total_seconds()¶
- Повертає загальну кількість секунд, що міститься в тривалості. Еквівалент - td / timedelta(seconds=1). Для одиниць інтервалу, відмінних від секунд, використовуйте напряму форму ділення (наприклад,- td / timedelta(microseconds=1)).- Зауважте, що для дуже великих інтервалів часу (понад 270 років на більшості платформ) цей метод втратить мікросекундну точність. - Added in version 3.2. 
Приклади використання: timedelta¶
Додатковий приклад нормалізації:
>>> # Components of another_year add up to exactly 365 days
>>> from datetime import timedelta
>>> year = timedelta(days=365)
>>> another_year = timedelta(weeks=40, days=84, hours=23,
...                          minutes=50, seconds=600)
>>> year == another_year
True
>>> year.total_seconds()
31536000.0
Приклади арифметики timedelta:
>>> from datetime import timedelta
>>> year = timedelta(days=365)
>>> ten_years = 10 * year
>>> ten_years
datetime.timedelta(days=3650)
>>> ten_years.days // 365
10
>>> nine_years = ten_years - year
>>> nine_years
datetime.timedelta(days=3285)
>>> three_years = nine_years // 3
>>> three_years, three_years.days // 365
(datetime.timedelta(days=1095), 3)
date Об’єкти¶
Об’єкт date представляє дату (рік, місяць і день) в ідеалізованому календарі, поточний григоріанський календар необмежено розширений в обох напрямках.
1 січня року 1 називається днем номер 1, 2 січня року 1 називається днем номер 2 і так далі. [2]
- class datetime.date(year, month, day)¶
- Всі аргументи необхідні. Аргументи мають бути цілими числами в таких діапазонах: - MINYEAR <= рік <= MAXYEAR
- 1 <= місяць <= 12
- 1 <= день <= кількість днів у заданому місяці та році
 - Якщо вказано аргумент поза цими діапазонами, виникає - ValueError.
Інші конструктори, усі методи класу:
- classmethod date.today()¶
- Повернути поточну місцеву дату. - Це еквівалентно - date.fromtimestamp(time.time()).
- classmethod date.fromtimestamp(timestamp)¶
- Повертає місцеву дату, що відповідає мітці часу POSIX, наприклад, яку повертає - time.time().- Це може спричинити помилку - OverflowError, якщо позначка часу виходить за межі діапазону значень, які підтримує функція C- localtime(), і- OSErrorу- localtime()невдача. Зазвичай це обмежується роками з 1970 по 2038 рік. Зауважте, що в системах без POSIX, які включають високосні секунди в своє поняття позначки часу, високосні секунди ігноруються- fromtimestamp().- Змінено в версії 3.3: Викликайте - OverflowErrorзамість- ValueError, якщо позначка часу виходить за межі діапазону значень, які підтримує функція C- localtime()платформи. Викликати- OSErrorзамість- ValueErrorу разі помилки- localtime().
- classmethod date.fromordinal(ordinal)¶
- Повертає дату, що відповідає пролептичному григоріанському порядковому номеру, де 1 січня 1 року має порядковий номер 1. - ValueErroris raised unless- 1 <= ordinal <= date.max.toordinal(). For any date- d,- date.fromordinal(d.toordinal()) == d.
- classmethod date.fromisoformat(date_string)¶
- Return a - datecorresponding to a date_string given in any valid ISO 8601 format, with the following exceptions:- Reduced precision dates are not currently supported ( - YYYY-MM,- YYYY).
- Extended date representations are not currently supported ( - ±YYYYYY-MM-DD).
- Ordinal dates are not currently supported ( - YYYY-OOO).
 - Приклади: - >>> from datetime import date >>> date.fromisoformat('2019-12-04') datetime.date(2019, 12, 4) >>> date.fromisoformat('20191204') datetime.date(2019, 12, 4) >>> date.fromisoformat('2021-W01-1') datetime.date(2021, 1, 4) - Added in version 3.7. - Змінено в версії 3.11: Previously, this method only supported the format - YYYY-MM-DD.
- classmethod date.fromisocalendar(year, week, day)¶
- Повертає - date, що відповідає календарній даті ISO, визначеній роком, тижнем і днем. Це зворотна функція- date.isocalendar().- Added in version 3.8. 
- classmethod date.strptime(date_string, format)¶
- Return a - datecorresponding to date_string, parsed according to format. This is equivalent to:- date(*(time.strptime(date_string, format)[0:3])) - ValueErroris raised if the date_string and format can’t be parsed by- time.strptime()or if it returns a value which isn’t a time tuple. See also strftime() and strptime() Behavior and- date.fromisoformat().- Примітка - If format specifies a day of month without a year a - DeprecationWarningis emitted. This is to avoid a quadrennial leap year bug in code seeking to parse only a month and day as the default year used in absence of one in the format is not a leap year. Such format values may raise an error as of Python 3.15. The workaround is to always include a year in your format. If parsing date_string values that do not have a year, explicitly add a year that is a leap year before parsing:- >>> from datetime import date >>> date_string = "02/29" >>> when = date.strptime(f"{date_string};1984", "%m/%d;%Y") # Avoids leap year bug. >>> when.strftime("%B %d") 'February 29' - Added in version 3.14. 
Атрибути класу:
- date.min¶
- Найраніша дата, яку можна представити, - date(MINYEAR, 1, 1).
- date.max¶
- Остання представлена дата, - date(MAXYEAR, 12, 31).
- date.resolution¶
- Найменша можлива різниця між об’єктами нерівних дат, - timedelta(days=1).
Атрибути екземпляра (тільки для читання):
- date.month¶
- Від 1 до 12 включно. 
- date.day¶
- Від 1 до числа днів у даному місяці даного року. 
Підтримувані операції:
| Операція | Результат | 
|---|---|
| 
 | 
 | 
| 
 | Computes  | 
| 
 | (3) | 
| date1 == date2date1 != date2 | Equality comparison. (4) | 
| дата1 < дата2date1 > date2date1 <= date2date1 >= date2 | Order comparison. (5) | 
Примітки:
- date2 пересувається вперед у часі, якщо - timedelta.days > 0, або назад,- timedelta.days < 0. Після цього- date2 - date1 == timedelta.days.- timedelta.secondsі- timedelta.microsecondsігноруються.- OverflowErrorвиникає, якщо- date2.yearбуде меншим за- MINYEARабо більшим за- MAXYEAR.
- timedelta.secondsі- timedelta.microsecondsігноруються.
- This is exact, and cannot overflow. - timedelta.secondsand- timedelta.microsecondsare 0, and- date2 + timedelta == date1after.
- dateobjects are equal if they represent the same date.- dateobjects that are not also- datetimeinstances are never equal to- datetimeobjects, even if they represent the same date.
- date1 is considered less than date2 when date1 precedes date2 in time. In other words, - date1 < date2if and only if- date1.toordinal() < date2.toordinal().- Order comparison between a - dateobject that is not also a- datetimeinstance and a- datetimeobject raises- TypeError.
Змінено в версії 3.13: Comparison between datetime object and an instance of
the date subclass that is not a datetime subclass
no longer converts the latter to date, ignoring the time part
and the time zone.
The default behavior can be changed by overriding the special comparison
methods in subclasses.
У логічних контекстах усі об’єкти date вважаються істинними.
Методи екземплярів:
- date.replace(year=self.year, month=self.month, day=self.day)¶
- Return a new - dateobject with the same values, but with specified parameters updated.- Приклад: - >>> from datetime import date >>> d = date(2002, 12, 31) >>> d.replace(day=26) datetime.date(2002, 12, 26) - The generic function - copy.replace()also supports- dateobjects.
- date.timetuple()¶
- Повертає - time.struct_time, наприклад, повертає- time.localtime().- Години, хвилини та секунди дорівнюють 0, а позначка літнього часу дорівнює -1. - d.timetuple()еквівалентний:- time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1)) - where - yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1is the day number within the current year starting with 1 for January 1st.
- date.toordinal()¶
- Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. For any - dateobject- d,- date.fromordinal(d.toordinal()) == d.
- date.weekday()¶
- Повертає день тижня як ціле число, де понеділок — 0, а неділя — 6. Наприклад, - date(2002, 12, 4).weekday() == 2, середа. Дивіться також- isoweekday().
- date.isoweekday()¶
- Повертає день тижня як ціле число, де понеділок — 1, а неділя — 7. Наприклад, - date(2002, 12, 4).isoweekday() == 3, середа. Дивіться також- weekday(),- isocalendar().
- date.isocalendar()¶
- Повертає об’єкт named tuple із трьома компонентами: - year,- weekі- weekday.- Календар ISO є широко використовуваним варіантом григоріанського календаря. [3] - Рік ISO складається з 52 або 53 повних тижнів, де тиждень починається в понеділок і закінчується в неділю. Перший тиждень року ISO — це перший (григоріанський) календарний тиждень року, що містить четвер. Це називається тижнем номер 1, і рік ISO того четверга такий же, як його григоріанський рік. - Наприклад, 2004 рік починається в четвер, тому перший тиждень 2004 року ISO починається в понеділок, 29 грудня 2003 року, і закінчується в неділю, 4 січня 2004 року: - >>> from datetime import date >>> date(2003, 12, 29).isocalendar() datetime.IsoCalendarDate(year=2004, week=1, weekday=1) >>> date(2004, 1, 4).isocalendar() datetime.IsoCalendarDate(year=2004, week=1, weekday=7) - Змінено в версії 3.9: Результат змінено з кортежу на named tuple. 
- date.isoformat()¶
- Повертає рядок, що представляє дату у форматі ISO 8601, - РРРР-ММ-ДД:- >>> from datetime import date >>> date(2002, 12, 4).isoformat() '2002-12-04' 
- date.__str__()¶
- For a date - d,- str(d)is equivalent to- d.isoformat().
- date.ctime()¶
- Повертає рядок, що представляє дату: - >>> from datetime import date >>> date(2002, 12, 4).ctime() 'Wed Dec 4 00:00:00 2002' - d.ctime()еквівалентний:- time.ctime(time.mktime(d.timetuple())) - на платформах, де рідна функція C - ctime()(яку- time.ctime()викликає, але яку- date.ctime()не викликає) відповідає стандарту C.
- date.strftime(format)¶
- Return a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values. See also strftime() and strptime() Behavior and - date.isoformat().
- date.__format__(format)¶
- Same as - date.strftime(). This makes it possible to specify a format string for a- dateobject in formatted string literals and when using- str.format(). See also strftime() and strptime() Behavior and- date.isoformat().
Приклади використання: date¶
Приклад підрахунку днів до події:
>>> import time
>>> from datetime import date
>>> today = date.today()
>>> today
datetime.date(2007, 12, 5)
>>> today == date.fromtimestamp(time.time())
True
>>> my_birthday = date(today.year, 6, 24)
>>> if my_birthday < today:
...     my_birthday = my_birthday.replace(year=today.year + 1)
...
>>> my_birthday
datetime.date(2008, 6, 24)
>>> time_to_birthday = abs(my_birthday - today)
>>> time_to_birthday.days
202
Ще приклади роботи з date:
>>> from datetime import date
>>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
>>> d
datetime.date(2002, 3, 11)
>>> # Methods related to formatting string output
>>> d.isoformat()
'2002-03-11'
>>> d.strftime("%d/%m/%y")
'11/03/02'
>>> d.strftime("%A %d. %B %Y")
'Monday 11. March 2002'
>>> d.ctime()
'Mon Mar 11 00:00:00 2002'
>>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
'The day is 11, the month is March.'
>>> # Methods for to extracting 'components' under different calendars
>>> t = d.timetuple()
>>> for i in t:
...     print(i)
2002                # year
3                   # month
11                  # day
0
0
0
0                   # weekday (0 = Monday)
70                  # 70th day in the year
-1
>>> ic = d.isocalendar()
>>> for i in ic:
...     print(i)
2002                # ISO year
11                  # ISO week number
1                   # ISO day number ( 1 = Monday )
>>> # A date object is immutable; all operations produce a new object
>>> d.replace(year=2005)
datetime.date(2005, 3, 11)
datetime Об’єкти¶
Об’єкт datetime — це єдиний об’єкт, який містить всю інформацію з об’єктів date і time.
Як і об’єкт date, datetime передбачає поточний григоріанський календар, розширений в обох напрямках; як і об’єкт time, datetime припускає, що кожен день становить рівно 3600*24 секунди.
Конструктор:
- class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)¶
- Аргументи рік, місяць і день є обов’язковими. tzinfo може бути - Noneабо екземпляром підкласу- tzinfo. Решта аргументів мають бути цілими числами в таких діапазонах:- MINYEAR <= рік <= MAXYEAR,
- 1 <= місяць <= 12,
- 1 <= день <= кількість днів у заданому місяці та році,
- 0 <= година < 24,
- 0 <= хвилина < 60,
- 0 <= секунда < 60,
- 0 <= мікросекунда < 1000000,
- згорнути [0, 1].
 - Якщо вказано аргумент поза цими діапазонами, виникає - ValueError.- Змінено в версії 3.6: Added the fold parameter. 
Інші конструктори, усі методи класу:
- classmethod datetime.today()¶
- Return the current local date and time, with - tzinfo- None.- Дорівнює: - datetime.fromtimestamp(time.time()) - Дивіться також - now(),- fromtimestamp().- Цей метод функціонально еквівалентний - now(), але без параметра- tz.
- classmethod datetime.now(tz=None)¶
- Повернути поточну місцеву дату й час. - Якщо необов’язковий аргумент tz має значення - Noneабо не вказано, це схоже на- today(), але, якщо можливо, надає більшу точність, ніж можна отримати, пройшовши через- time.time()мітка часу (наприклад, це можливо на платформах, що забезпечують функцію C- gettimeofday()).- Якщо tz не є - None, він має бути екземпляром підкласу- tzinfo, а поточні дата й час перетворюються на часовий пояс tz.- Цій функції надається перевага над - today()і- utcnow().- Примітка - Subsequent calls to - datetime.now()may return the same instant depending on the precision of the underlying clock.
- classmethod datetime.utcnow()¶
- Повертає поточну дату й час за UTC за допомогою - tzinfo- None.- Це схоже на - now(), але повертає поточну дату та час у форматі UTC як простий об’єкт- datetime. Відомий поточний UTC datetime можна отримати, викликавши- datetime.now(timezone.utc). Дивіться також- now().- Попередження - Оскільки наївні об’єкти - datetimeрозглядаються багатьма методами- datetimeяк місцевий час, бажано використовувати відомі дати для представлення часу в UTC. Таким чином, рекомендований спосіб створити об’єкт, що представляє поточний час у UTC, — це викликати- datetime.now(timezone.utc).- Застаріло починаючи з версії 3.12: Use - datetime.now()with- UTCinstead.
- classmethod datetime.fromtimestamp(timestamp, tz=None)¶
- Повертає локальну дату й час, що відповідають мітці часу POSIX, наприклад, повертає - time.time(). Якщо необов’язковий аргумент tz має значення- Noneабо не вказано, позначка часу перетворюється на локальну дату й час платформи, а повернутий об’єкт- datetimeє простим.- Якщо tz не є - None, він має бути екземпляром підкласу- tzinfo, а мітка часу перетворюється на часовий пояс tz.- fromtimestamp()може викликати- OverflowError, якщо мітка часу виходить за межі діапазону значень, які підтримуються функціями платформи C- localtime()або- gmtime(), і- OSErrorпід час помилки- localtime()або- gmtime(). Зазвичай це обмежується роками з 1970 по 2038 рік. Зауважте, що в системах без POSIX, які включають високосні секунди в своє поняття позначки часу, високосні секунди ігноруються- fromtimestamp(), і тоді можна мати дві мітки часу, що відрізняються на секунду, що дає ідентичні об’єкти- datetime. Цей метод є кращим перед- utcfromtimestamp().- Змінено в версії 3.3: Викликайте - OverflowErrorзамість- ValueError, якщо позначка часу виходить за межі діапазону значень, які підтримують функції C- localtime()або- gmtime()платформи. Викликати- OSErrorзамість- ValueErrorу разі помилки- localtime()або- gmtime().- Змінено в версії 3.6: - fromtimestamp()може повертати екземпляри з- fold, встановленим на 1.
- classmethod datetime.utcfromtimestamp(timestamp)¶
- Повертає UTC - datetime, що відповідає мітці часу POSIX, з- tzinfo- None. (Отриманий об’єкт наївний.)- Це може спричинити помилку - OverflowError, якщо позначка часу виходить за межі значень, які підтримує функція платформи C- gmtime(), і- OSErrorна- gmtime()невдача. Зазвичай це обмежується роками з 1970 по 2038 рік.- Щоб отримати відомий об’єкт - datetime, викличте- fromtimestamp():- datetime.fromtimestamp(timestamp, timezone.utc) - На POSIX-сумісних платформах це еквівалентно такому виразу: - datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp) - за винятком останньої формули, яка завжди підтримує повний діапазон років: від - MINYEARдо- MAXYEARвключно.- Попередження - Оскільки наївні об’єкти - datetimeрозглядаються багатьма методами- datetimeяк місцевий час, бажано використовувати відомі дати для представлення часу в UTC. Таким чином, рекомендований спосіб створити об’єкт, що представляє конкретну позначку часу в UTC, — це викликати- datetime.fromtimestamp(timestamp, tz=timezone.utc).- Змінено в версії 3.3: Викликайте - OverflowErrorзамість- ValueError, якщо позначка часу виходить за межі діапазону значень, які підтримує функція C- gmtime()платформи. Викликати- OSErrorзамість- ValueErrorу разі помилки- gmtime().- Застаріло починаючи з версії 3.12: Use - datetime.fromtimestamp()with- UTCinstead.
- classmethod datetime.fromordinal(ordinal)¶
- Повертає - datetime, що відповідає пролептичному григоріанському порядковому номеру, де 1 січня року 1 має порядковий номер 1.- ValueErrorвиникає, якщо не- 1 <= порядковий <= datetime.max.toordinal(). Година, хвилина, секунда та мікросекунда результату дорівнюють 0, а- tzinfo—- None.
- classmethod datetime.combine(date, time, tzinfo=time.tzinfo)¶
- Return a new - datetimeobject whose date components are equal to the given- dateobject’s, and whose time components are equal to the given- timeobject’s. If the tzinfo argument is provided, its value is used to set the- tzinfoattribute of the result, otherwise the- tzinfoattribute of the time argument is used. If the date argument is a- datetimeobject, its time components and- tzinfoattributes are ignored.- For any - datetimeobject- d,- d == datetime.combine(d.date(), d.time(), d.tzinfo).- Змінено в версії 3.6: Додано аргумент tzinfo. 
- classmethod datetime.fromisoformat(date_string)¶
- Return a - datetimecorresponding to a date_string in any valid ISO 8601 format, with the following exceptions:- Time zone offsets may have fractional seconds. 
- The - Tseparator may be replaced by any single unicode character.
- Fractional hours and minutes are not supported. 
- Reduced precision dates are not currently supported ( - YYYY-MM,- YYYY).
- Extended date representations are not currently supported ( - ±YYYYYY-MM-DD).
- Ordinal dates are not currently supported ( - YYYY-OOO).
 - Приклади: - >>> from datetime import datetime >>> datetime.fromisoformat('2011-11-04') datetime.datetime(2011, 11, 4, 0, 0) >>> datetime.fromisoformat('20111104') datetime.datetime(2011, 11, 4, 0, 0) >>> datetime.fromisoformat('2011-11-04T00:05:23') datetime.datetime(2011, 11, 4, 0, 5, 23) >>> datetime.fromisoformat('2011-11-04T00:05:23Z') datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc) >>> datetime.fromisoformat('20111104T000523') datetime.datetime(2011, 11, 4, 0, 5, 23) >>> datetime.fromisoformat('2011-W01-2T00:05:23.283') datetime.datetime(2011, 1, 4, 0, 5, 23, 283000) >>> datetime.fromisoformat('2011-11-04 00:05:23.283') datetime.datetime(2011, 11, 4, 0, 5, 23, 283000) >>> datetime.fromisoformat('2011-11-04 00:05:23.283+00:00') datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc) >>> datetime.fromisoformat('2011-11-04T00:05:23+04:00') datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400))) - Added in version 3.7. - Змінено в версії 3.11: Previously, this method only supported formats that could be emitted by - date.isoformat()or- datetime.isoformat().
- classmethod datetime.fromisocalendar(year, week, day)¶
- Повертає - datetime, що відповідає календарній даті ISO, визначеній роком, тижнем і днем. Компоненти datetime, що не є датою, заповнюються стандартними значеннями за замовчуванням. Це зворотна функція- datetime.isocalendar().- Added in version 3.8. 
- classmethod datetime.strptime(date_string, format)¶
- Повертає - datetime, що відповідає рядку_дати, розібраному відповідно до формату.- If format does not contain microseconds or time zone information, this is equivalent to: - datetime(*(time.strptime(date_string, format)[0:6])) - ValueErroris raised if the date_string and format can’t be parsed by- time.strptime()or if it returns a value which isn’t a time tuple. See also strftime() and strptime() Behavior and- datetime.fromisoformat().- Змінено в версії 3.13: If format specifies a day of month without a year a - DeprecationWarningis now emitted. This is to avoid a quadrennial leap year bug in code seeking to parse only a month and day as the default year used in absence of one in the format is not a leap year. Such format values may raise an error as of Python 3.15. The workaround is to always include a year in your format. If parsing date_string values that do not have a year, explicitly add a year that is a leap year before parsing:- >>> from datetime import datetime >>> date_string = "02/29" >>> when = datetime.strptime(f"{date_string};1984", "%m/%d;%Y") # Avoids leap year bug. >>> when.strftime("%B %d") 'February 29' 
Атрибути класу:
- datetime.max¶
- Останній представлений - datetime,- datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None).
- datetime.resolution¶
- Найменша можлива різниця між нерівними об’єктами - datetime,- timedelta(microseconds=1).
Атрибути екземпляра (тільки для читання):
- datetime.month¶
- Від 1 до 12 включно. 
- datetime.day¶
- Від 1 до числа днів у даному місяці даного року. 
- datetime.hour¶
- У діапазоні (24). 
- datetime.minute¶
- У - діапазоні (60).
- datetime.second¶
- У - діапазоні (60).
- datetime.microsecond¶
- У - діапазоні (1000 000).
- datetime.tzinfo¶
- Об’єкт передається як аргумент tzinfo конструктору - datetimeабо- None, якщо жодного не було передано.
- datetime.fold¶
- In - [0, 1]. Used to disambiguate wall times during a repeated interval. (A repeated interval occurs when clocks are rolled back at the end of daylight saving time or when the UTC offset for the current zone is decreased for political reasons.) The values 0 and 1 represent, respectively, the earlier and later of the two moments with the same wall time representation.- Added in version 3.6. 
Підтримувані операції:
| Операція | Результат | 
|---|---|
| 
 | (1) | 
| 
 | (2) | 
| 
 | (3) | 
| datetime1 == datetime2datetime1 != datetime2 | Equality comparison. (4) | 
| датачас1 < датачас2datetime1 > datetime2datetime1 <= datetime2datetime1 >= datetime2 | Order comparison. (5) | 
- datetime2is a duration of- timedeltaremoved from- datetime1, moving forward in time if- timedelta.days > 0, or backward if- timedelta.days < 0. The result has the same- tzinfoattribute as the input datetime, and- datetime2 - datetime1 == timedeltaafter.- OverflowErroris raised if- datetime2.yearwould be smaller than- MINYEARor larger than- MAXYEAR. Note that no time zone adjustments are done even if the input is an aware object.
- Computes the - datetime2such that- datetime2 + timedelta == datetime1. As for addition, the result has the same- tzinfoattribute as the input datetime, and no time zone adjustments are done even if the input is aware.
- Віднімання - datetimeвід- datetimeвизначається, лише якщо обидва операнди наївні, або якщо обидва знають. Якщо один знає, а інший наївний, виникає- TypeError.- If both are naive, or both are aware and have the same - tzinfoattribute, the- tzinfoattributes are ignored, and the result is a- timedeltaobject- tsuch that- datetime2 + t == datetime1. No time zone adjustments are done in this case.- If both are aware and have different - tzinfoattributes,- a-bacts as if- aand- bwere first converted to naive UTC datetimes. The result is- (a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) - b.utcoffset())except that the implementation never overflows.
- datetimeobjects are equal if they represent the same date and time, taking into account the time zone.- Naive and aware - datetimeobjects are never equal.- If both comparands are aware, and have the same - tzinfoattribute, the- tzinfoand- foldattributes are ignored and the base datetimes are compared. If both comparands are aware and have different- tzinfoattributes, the comparison acts as comparands were first converted to UTC datetimes except that the implementation never overflows.- datetimeinstances in a repeated interval are never equal to- datetimeinstances in other time zone.
- datetime1 is considered less than datetime2 when datetime1 precedes datetime2 in time, taking into account the time zone. - Order comparison between naive and aware - datetimeobjects raises- TypeError.- If both comparands are aware, and have the same - tzinfoattribute, the- tzinfoand- foldattributes are ignored and the base datetimes are compared. If both comparands are aware and have different- tzinfoattributes, the comparison acts as comparands were first converted to UTC datetimes except that the implementation never overflows.
Змінено в версії 3.3: Порівняння рівності між обізнаними та наївними екземплярами datetime не викликає TypeError.
Змінено в версії 3.13: Comparison between datetime object and an instance of
the date subclass that is not a datetime subclass
no longer converts the latter to date, ignoring the time part
and the time zone.
The default behavior can be changed by overriding the special comparison
methods in subclasses.
Методи екземплярів:
- datetime.time()¶
- Повертає об’єкт - timeіз тією самою годиною, хвилиною, секундою, мікросекундою та згортанням.- tzinfo— це- None. Дивіться також метод- timetz().- Змінено в версії 3.6: Значення згортання копіюється до повернутого об’єкта - time.
- datetime.timetz()¶
- Повертає об’єкт - timeз такими самими атрибутами: година, хвилина, секунда, мікросекунда, згортання та tzinfo. Дивіться також метод- time().- Змінено в версії 3.6: Значення згортання копіюється до повернутого об’єкта - time.
- datetime.replace(year=self.year, month=self.month, day=self.day, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, *, fold=0)¶
- Return a new - datetimeobject with the same attributes, but with specified parameters updated. Note that- tzinfo=Nonecan be specified to create a naive datetime from an aware datetime with no conversion of date and time data.- datetimeobjects are also supported by generic function- copy.replace().- Змінено в версії 3.6: Added the fold parameter. 
- datetime.astimezone(tz=None)¶
- Повертає об’єкт - datetimeз новим атрибутом- tzinfotz, регулюючи дані дати й часу таким чином, щоб результат був таким самим часом UTC, як self, але в tz місцевий час.- If provided, tz must be an instance of a - tzinfosubclass, and its- utcoffset()and- dst()methods must not return- None. If self is naive, it is presumed to represent time in the system time zone.- If called without arguments (or with - tz=None) the system local time zone is assumed for the target time zone. The- .tzinfoattribute of the converted datetime instance will be set to an instance of- timezonewith the zone name and offset obtained from the OS.- If - self.tzinfois tz,- self.astimezone(tz)is equal to self: no adjustment of date or time data is performed. Else the result is local time in the time zone tz, representing the same UTC time as self: after- astz = dt.astimezone(tz),- astz - astz.utcoffset()will have the same date and time data as- dt - dt.utcoffset().- If you merely want to attach a - timezoneobject tz to a datetime dt without adjustment of date and time data, use- dt.replace(tzinfo=tz). If you merely want to remove the- timezoneobject from an aware datetime dt without conversion of date and time data, use- dt.replace(tzinfo=None).- Зауважте, що стандартний метод - tzinfo.fromutc()можна замінити в підкласі- tzinfo, щоб вплинути на результат, який повертає- astimezone(). Ігноруючи випадки помилок,- astimezone()діє як:- def astimezone(self, tz): if self.tzinfo is tz: return self # Convert self to UTC, and attach the new timezone object. utc = (self - self.utcoffset()).replace(tzinfo=tz) # Convert from UTC to tz's local time. return tz.fromutc(utc) - Змінено в версії 3.3: tz тепер можна опустити. - Змінено в версії 3.6: Метод - astimezone()тепер можна викликати в простих екземплярах, які, як припускається, представляють місцевий час системи.
- datetime.utcoffset()¶
- Якщо - tzinfoмає значення- None, повертає- None, інакше повертає- self.tzinfo.utcoffset(self)і викликає виняток, якщо останній не повертає- Noneабо об’єкт- timedeltaз величиною менше одного дня.- Змінено в версії 3.7: Зсув UTC не обмежений цілою кількістю хвилин. 
- datetime.dst()¶
- Якщо - tzinfoмає значення- None, повертає- None, інакше повертає- self.tzinfo.dst(self)і викликає виняток, якщо останній не повертає- Noneабо об’єкт- timedeltaз величиною менше одного дня.- Змінено в версії 3.7: Зміщення літнього часу не обмежується цілою кількістю хвилин. 
- datetime.tzname()¶
- Якщо - tzinfoмає значення- None, повертає- None, інакше повертає- self.tzinfo.tzname(self), викликає виняток, якщо останній не повертає- Noneабо рядковий об’єкт,
- datetime.timetuple()¶
- Повертає - time.struct_time, наприклад, повертає- time.localtime().- d.timetuple()еквівалентний:- time.struct_time((d.year, d.month, d.day, d.hour, d.minute, d.second, d.weekday(), yday, dst)) - where - yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1is the day number within the current year starting with 1 for January 1st. The- tm_isdstflag of the result is set according to the- dst()method:- tzinfois- Noneor- dst()returns- None,- tm_isdstis set to- -1; else if- dst()returns a non-zero value,- tm_isdstis set to 1; else- tm_isdstis set to 0.
- datetime.utctimetuple()¶
- If - datetimeinstance- dis naive, this is the same as- d.timetuple()except that- tm_isdstis forced to 0 regardless of what- d.dst()returns. DST is never in effect for a UTC time.- If - dis aware,- dis normalized to UTC time, by subtracting- d.utcoffset(), and a- time.struct_timefor the normalized time is returned.- tm_isdstis forced to 0. Note that an- OverflowErrormay be raised if- d.yearwas- MINYEARor- MAXYEARand UTC adjustment spills over a year boundary.- Попередження - Because naive - datetimeobjects are treated by many- datetimemethods as local times, it is preferred to use aware datetimes to represent times in UTC; as a result, using- datetime.utctimetuple()may give misleading results. If you have a naive- datetimerepresenting UTC, use- datetime.replace(tzinfo=timezone.utc)to make it aware, at which point you can use- datetime.timetuple().
- datetime.toordinal()¶
- Повертає пролептичний григоріанський порядковий номер дати. Те саме, що - self.date().toordinal().
- datetime.timestamp()¶
- Повертає позначку часу POSIX, що відповідає екземпляру - datetime. Значення, що повертається, є- float, подібне до того, яке повертає- time.time().- Naive - datetimeinstances are assumed to represent local time and this method relies on the platform C- mktime()function to perform the conversion. Since- datetimesupports wider range of values than- mktime()on many platforms, this method may raise- OverflowErroror- OSErrorfor times far in the past or far in the future.- Для екземплярів aware - datetimeзначення, що повертається, обчислюється як:- (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds() - Added in version 3.3. - Змінено в версії 3.6: Метод - timestamp()використовує атрибут- fold, щоб усунути неоднозначність часу протягом повторюваного інтервалу.- Примітка - There is no method to obtain the POSIX timestamp directly from a naive - datetimeinstance representing UTC time. If your application uses this convention and your system time zone is not set to UTC, you can obtain the POSIX timestamp by supplying- tzinfo=timezone.utc:- timestamp = dt.replace(tzinfo=timezone.utc).timestamp() - або шляхом безпосереднього обчислення позначки часу: - timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1) 
- datetime.weekday()¶
- Повертає день тижня як ціле число, де понеділок дорівнює 0, а неділя – 6. Те саме, що - self.date().weekday(). Дивіться також- isoweekday().
- datetime.isoweekday()¶
- Повертає день тижня як ціле число, де понеділок — 1, а неділя — 7. Те саме, що - self.date().isoweekday(). Дивіться також- weekday(),- isocalendar().
- datetime.isocalendar()¶
- Повертає named tuple із трьома компонентами: - рік,- тижденьі- день тижня. Те саме, що- self.date().isocalendar().
- datetime.isoformat(sep='T', timespec='auto')¶
- Повертає рядок, що представляє дату й час у форматі ISO 8601: - РРРР-ММ-ДДТГГ:ММ:СС.ffffff, якщо- microsecondне дорівнює 0
- РРРР-ММ-ДДТГГ:ХМ:СС, якщо- microsecondдорівнює 0
 - Якщо - utcoffset()не повертає- None, додається рядок із зміщенням UTC:- РРРР-ММ-ДДТГГ:ММ:СС.ffffff+ГГ:ММ[:СС[.ffffff]], якщо- microsecondне дорівнює 0
- РРРР-ММ-ДДТГГ:ММ:СС+ГГ:ХМ[:СС[.ffffff]], якщо- microsecondдорівнює 0
 - Приклади: - >>> from datetime import datetime, timezone >>> datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat() '2019-05-18T15:17:08.132263' >>> datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat() '2019-05-18T15:17:00+00:00' - Необов’язковий аргумент sep (за замовчуванням - 'T') є односимвольним роздільником, який розміщується між частинами дати та часу результату. Наприклад:- >>> from datetime import tzinfo, timedelta, datetime >>> class TZ(tzinfo): ... """A time zone with an arbitrary, constant -06:39 offset.""" ... def utcoffset(self, dt): ... return timedelta(hours=-6, minutes=-39) ... >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') '2002-12-25 00:00:00-06:39' >>> datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat() '2009-11-27T00:00:00.000100-06:39' - Необов’язковий аргумент timespec визначає кількість додаткових компонентів часу, які потрібно включити (за замовчуванням це - 'auto'). Це може бути одне з наступного:- 'auto': те саме, що- 'seconds', якщо- microsecondдорівнює 0, те ж саме, що- 'microseconds'інакше.
- 'hours': Додайте- hourу двозначному форматі- HH.
- 'seconds': включайте- hour,- minuteі- secondу форматі- HH:MM:SS.
- 'milliseconds': включити повний час, але скоротити дробову другу частину до мілісекунд. Формат- HH:MM:SS.sss.
- 'microseconds': включіть повний час у форматі- HH:MM:SS.ffffff.
 - Примітка - Виключені компоненти часу скорочуються, а не округлюються. - ValueErrorбуде викликано через недійсний аргумент timespec:- >>> from datetime import datetime >>> datetime.now().isoformat(timespec='minutes') '2002-12-25T00:00' >>> dt = datetime(2015, 1, 1, 12, 30, 59, 0) >>> dt.isoformat(timespec='microseconds') '2015-01-01T12:30:59.000000' - Змінено в версії 3.6: Додано параметр специфікації часу. 
- datetime.ctime()¶
- Повертає рядок, що представляє дату й час: - >>> from datetime import datetime >>> datetime(2002, 12, 4, 20, 30, 40).ctime() 'Wed Dec 4 20:30:40 2002' - Рядок виводу не включатиме інформацію про часовий пояс, незалежно від того, чи є введення відомим чи простим. - d.ctime()еквівалентний:- time.ctime(time.mktime(d.timetuple())) - на платформах, де рідна функція C - ctime()(яку- time.ctime()викликає, але яку- datetime.ctime()не викликає) відповідає стандарту C.
- datetime.strftime(format)¶
- Return a string representing the date and time, controlled by an explicit format string. See also strftime() and strptime() Behavior and - datetime.isoformat().
- datetime.__format__(format)¶
- Same as - datetime.strftime(). This makes it possible to specify a format string for a- datetimeobject in formatted string literals and when using- str.format(). See also strftime() and strptime() Behavior and- datetime.isoformat().
Приклади використання: datetime¶
Examples of working with datetime objects:
>>> from datetime import datetime, date, time, timezone
>>> # Using datetime.combine()
>>> d = date(2005, 7, 14)
>>> t = time(12, 30)
>>> datetime.combine(d, t)
datetime.datetime(2005, 7, 14, 12, 30)
>>> # Using datetime.now()
>>> datetime.now()
datetime.datetime(2007, 12, 6, 16, 29, 43, 79043)   # GMT +1
>>> datetime.now(timezone.utc)
datetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone.utc)
>>> # Using datetime.strptime()
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)
>>> # Using datetime.timetuple() to get tuple of all attributes
>>> tt = dt.timetuple()
>>> for it in tt:
...     print(it)
...
2006    # year
11      # month
21      # day
16      # hour
30      # minute
0       # second
1       # weekday (0 = Monday)
325     # number of days since 1st January
-1      # dst - method tzinfo.dst() returned None
>>> # Date in ISO format
>>> ic = dt.isocalendar()
>>> for it in ic:
...     print(it)
...
2006    # ISO year
47      # ISO week
2       # ISO weekday
>>> # Formatting a datetime
>>> dt.strftime("%A, %d. %B %Y %I:%M%p")
'Tuesday, 21. November 2006 04:30PM'
>>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
'The day is 21, the month is November, the time is 04:30PM.'
У наведеному нижче прикладі визначено підклас tzinfo, який збирає інформацію про часовий пояс для Кабула, Афганістан, який використовував +4 UTC до 1945 року, а потім +4:30 UTC після цього:
from datetime import timedelta, datetime, tzinfo, timezone
class KabulTz(tzinfo):
    # Kabul used +4 until 1945, when they moved to +4:30
    UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc)
    def utcoffset(self, dt):
        if dt.year < 1945:
            return timedelta(hours=4)
        elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, 30):
            # An ambiguous ("imaginary") half-hour range representing
            # a 'fold' in time due to the shift from +4 to +4:30.
            # If dt falls in the imaginary range, use fold to decide how
            # to resolve. See PEP495.
            return timedelta(hours=4, minutes=(30 if dt.fold else 0))
        else:
            return timedelta(hours=4, minutes=30)
    def fromutc(self, dt):
        # Follow same validations as in datetime.tzinfo
        if not isinstance(dt, datetime):
            raise TypeError("fromutc() requires a datetime argument")
        if dt.tzinfo is not self:
            raise ValueError("dt.tzinfo is not self")
        # A custom implementation is required for fromutc as
        # the input to this function is a datetime with utc values
        # but with a tzinfo set to self.
        # See datetime.astimezone or fromtimestamp.
        if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE:
            return dt + timedelta(hours=4, minutes=30)
        else:
            return dt + timedelta(hours=4)
    def dst(self, dt):
        # Kabul does not observe daylight saving time.
        return timedelta(0)
    def tzname(self, dt):
        if dt >= self.UTC_MOVE_DATE:
            return "+04:30"
        return "+04"
Використання KabulTz зверху:
>>> tz1 = KabulTz()
>>> # Datetime before the change
>>> dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1)
>>> print(dt1.utcoffset())
4:00:00
>>> # Datetime after the change
>>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1)
>>> print(dt2.utcoffset())
4:30:00
>>> # Convert datetime to another time zone
>>> dt3 = dt2.astimezone(timezone.utc)
>>> dt3
datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc)
>>> dt2
datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz())
>>> dt2 == dt3
True
time Об’єкти¶
A time object represents a (local) time of day, independent of any particular
day, and subject to adjustment via a tzinfo object.
- class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)¶
- Усі аргументи необов’язкові. tzinfo може бути - Noneабо екземпляром підкласу- tzinfo. Решта аргументів мають бути цілими числами в таких діапазонах:- 0 <= година < 24,
- 0 <= хвилина < 60,
- 0 <= секунда < 60,
- 0 <= мікросекунда < 1000000,
- згорнути [0, 1].
 - If an argument outside those ranges is given, - ValueErroris raised. All default to 0 except tzinfo, which defaults to- None.
Атрибути класу:
- time.resolution¶
- Найменша можлива різниця між нерівними об’єктами - time,- timedelta(microseconds=1), хоча зауважте, що арифметика в об’єктах- timeне підтримується.
Атрибути екземпляра (тільки для читання):
- time.hour¶
- У діапазоні (24). 
- time.minute¶
- У - діапазоні (60).
- time.second¶
- У - діапазоні (60).
- time.microsecond¶
- У - діапазоні (1000 000).
- time.tzinfo¶
- Об’єкт, переданий як аргумент tzinfo конструктору - time, або- None, якщо жодного не було передано.
- time.fold¶
- In - [0, 1]. Used to disambiguate wall times during a repeated interval. (A repeated interval occurs when clocks are rolled back at the end of daylight saving time or when the UTC offset for the current zone is decreased for political reasons.) The values 0 and 1 represent, respectively, the earlier and later of the two moments with the same wall time representation.- Added in version 3.6. 
time objects support equality and order comparisons,
where a is considered less than b when a precedes b in time.
Naive and aware time objects are never equal.
Order comparison between naive and aware time objects raises
TypeError.
If both comparands are aware, and have the same tzinfo
attribute, the tzinfo and fold attributes are
ignored and the base times are compared. If both comparands are aware and
have different tzinfo attributes, the comparands are first adjusted by
subtracting their UTC offsets (obtained from self.utcoffset()).
Змінено в версії 3.3: Equality comparisons between aware and naive time instances
don’t raise TypeError.
У логічних контекстах об’єкт time завжди вважається істинним.
Змінено в версії 3.5: До Python 3.5 об’єкт time вважався хибним, якщо він представляв північ за UTC. Така поведінка вважалася незрозумілою та спроможною до помилок, і її було видалено в Python 3.5. Дивіться bpo-13936 для отримання повної інформації.
Other constructors:
- classmethod time.fromisoformat(time_string)¶
- Return a - timecorresponding to a time_string in any valid ISO 8601 format, with the following exceptions:- Time zone offsets may have fractional seconds. 
- The leading - T, normally required in cases where there may be ambiguity between a date and a time, is not required.
- Fractional seconds may have any number of digits (anything beyond 6 will be truncated). 
- Fractional hours and minutes are not supported. 
 - Приклади: - >>> from datetime import time >>> time.fromisoformat('04:23:01') datetime.time(4, 23, 1) >>> time.fromisoformat('T04:23:01') datetime.time(4, 23, 1) >>> time.fromisoformat('T042301') datetime.time(4, 23, 1) >>> time.fromisoformat('04:23:01.000384') datetime.time(4, 23, 1, 384) >>> time.fromisoformat('04:23:01,000384') datetime.time(4, 23, 1, 384) >>> time.fromisoformat('04:23:01+04:00') datetime.time(4, 23, 1, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400))) >>> time.fromisoformat('04:23:01Z') datetime.time(4, 23, 1, tzinfo=datetime.timezone.utc) >>> time.fromisoformat('04:23:01+00:00') datetime.time(4, 23, 1, tzinfo=datetime.timezone.utc) - Added in version 3.7. - Змінено в версії 3.11: Previously, this method only supported formats that could be emitted by - time.isoformat().
- classmethod time.strptime(date_string, format)¶
- Return a - timecorresponding to date_string, parsed according to format.- If format does not contain microseconds or timezone information, this is equivalent to: - time(*(time.strptime(date_string, format)[3:6])) - ValueErroris raised if the date_string and format cannot be parsed by- time.strptime()or if it returns a value which is not a time tuple. See also strftime() and strptime() Behavior and- time.fromisoformat().- Added in version 3.14. 
Методи екземплярів:
- time.replace(hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, *, fold=0)¶
- Return a new - timewith the same values, but with specified parameters updated. Note that- tzinfo=Nonecan be specified to create a naive- timefrom an aware- time, without conversion of the time data.- timeobjects are also supported by generic function- copy.replace().- Змінено в версії 3.6: Added the fold parameter. 
- time.isoformat(timespec='auto')¶
- Повертає рядок, що представляє час у форматі ISO 8601, один із: - HH:MM:SS.ffffff, якщо- microsecondне дорівнює 0
- ГГ:ХХ:СС, якщо- microsecondдорівнює 0
- HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]], якщо- utcoffset()не повертає- None
- ГГ:ХМ:СС+ГГ:ХМ[:СС[.ffffff]], якщо- microsecondдорівнює 0 і- utcoffset()не повертає- None
 - Необов’язковий аргумент timespec визначає кількість додаткових компонентів часу, які потрібно включити (за замовчуванням це - 'auto'). Це може бути одне з наступного:- 'auto': те саме, що- 'seconds', якщо- microsecondдорівнює 0, те ж саме, що- 'microseconds'інакше.
- 'hours': Додайте- hourу двозначному форматі- HH.
- 'seconds': включайте- hour,- minuteі- secondу форматі- HH:MM:SS.
- 'milliseconds': включити повний час, але скоротити дробову другу частину до мілісекунд. Формат- HH:MM:SS.sss.
- 'microseconds': включіть повний час у форматі- HH:MM:SS.ffffff.
 - Примітка - Виключені компоненти часу скорочуються, а не округлюються. - ValueErrorбуде викликано через недійсний аргумент timespec.- Приклад: - >>> from datetime import time >>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes') '12:34' >>> dt = time(hour=12, minute=34, second=56, microsecond=0) >>> dt.isoformat(timespec='microseconds') '12:34:56.000000' >>> dt.isoformat(timespec='auto') '12:34:56' - Змінено в версії 3.6: Додано параметр специфікації часу. 
- time.__str__()¶
- For a time - t,- str(t)is equivalent to- t.isoformat().
- time.strftime(format)¶
- Return a string representing the time, controlled by an explicit format string. See also strftime() and strptime() Behavior and - time.isoformat().
- time.__format__(format)¶
- Same as - time.strftime(). This makes it possible to specify a format string for a- timeobject in formatted string literals and when using- str.format(). See also strftime() and strptime() Behavior and- time.isoformat().
- time.utcoffset()¶
- Якщо - tzinfoмає значення- None, повертає- None, інакше повертає- self.tzinfo.utcoffset(None)і викликає виняток, якщо останній не повертає- Noneабо об’єкт- timedeltaз величиною менше одного дня.- Змінено в версії 3.7: Зсув UTC не обмежений цілою кількістю хвилин. 
- time.dst()¶
- Якщо - tzinfoмає значення- None, повертає- None, інакше повертає- self.tzinfo.dst(None)і викликає виняток, якщо останній не повертає- Noneабо об’єкт- timedeltaз величиною менше одного дня.- Змінено в версії 3.7: Зміщення літнього часу не обмежується цілою кількістю хвилин. 
- time.tzname()¶
- Якщо - tzinfoмає значення- None, повертає- None, інакше повертає- self.tzinfo.tzname(None)або викликає виняток, якщо останній не повертає- Noneабо рядковий об’єкт.
Приклади використання: time¶
Приклади роботи з об’єктом time:
>>> from datetime import time, tzinfo, timedelta
>>> class TZ1(tzinfo):
...     def utcoffset(self, dt):
...         return timedelta(hours=1)
...     def dst(self, dt):
...         return timedelta(0)
...     def tzname(self,dt):
...         return "+01:00"
...     def  __repr__(self):
...         return f"{self.__class__.__name__}()"
...
>>> t = time(12, 10, 30, tzinfo=TZ1())
>>> t
datetime.time(12, 10, 30, tzinfo=TZ1())
>>> t.isoformat()
'12:10:30+01:00'
>>> t.dst()
datetime.timedelta(0)
>>> t.tzname()
'+01:00'
>>> t.strftime("%H:%M:%S %Z")
'12:10:30 +01:00'
>>> 'The {} is {:%H:%M}.'.format("time", t)
'The time is 12:10.'
tzinfo Об’єкти¶
- class datetime.tzinfo¶
- Це абстрактний базовий клас, що означає, що цей клас не повинен створюватися безпосередньо. Визначте підклас - tzinfoдля отримання інформації про певний часовий пояс.- Екземпляр (конкретного підкласу) - tzinfoможна передати конструкторам для об’єктів- datetimeі- time. Останні об’єкти розглядають свої атрибути як місцевий час, а об’єкт- tzinfoпідтримує методи, які виявляють зміщення місцевого часу від UTC, назви часового поясу та зміщення літнього часу, усе відносно об’єкта дати чи часу передано їм.- You need to derive a concrete subclass, and (at least) supply implementations of the standard - tzinfomethods needed by the- datetimemethods you use. The- datetimemodule provides- timezone, a simple concrete subclass of- tzinfowhich can represent time zones with fixed offset from UTC such as UTC itself or North American EST and EDT.- Special requirement for pickling: A - tzinfosubclass must have an- __init__()method that can be called with no arguments, otherwise it can be pickled but possibly not unpickled again. This is a technical requirement that may be relaxed in the future.- A concrete subclass of - tzinfomay need to implement the following methods. Exactly which methods are needed depends on the uses made of aware- datetimeobjects. If in doubt, simply implement all of them.
- tzinfo.utcoffset(dt)¶
- Повертає зміщення місцевого часу від UTC, як об’єкт - timedelta, який є позитивним на схід від UTC. Якщо місцевий час на захід від UTC, це значення має бути від’ємним.- Це загальне зміщення від UTC; наприклад, якщо об’єкт - tzinfoпредставляє коригування часового поясу та літнього часу,- utcoffset()має повернути їх суму. Якщо зсув UTC невідомий, поверніть- None. Інакше повернене значення має бути об’єктом- timedeltaстрого між- -timedelta(hours=24)і- timedelta(hours=24)(величина зміщення має бути меншою за один день ). Більшість реалізацій- utcoffset(), ймовірно, виглядатимуть як одне з цих двох:- return CONSTANT # fixed-offset class return CONSTANT + self.dst(dt) # daylight-aware class - Якщо - utcoffset()не повертає- None,- dst()також не має повертати- None.- Стандартна реалізація - utcoffset()викликає- NotImplementedError.- Змінено в версії 3.7: Зсув UTC не обмежений цілою кількістю хвилин. 
- tzinfo.dst(dt)¶
- Повертає коригування літнього часу (DST) як об’єкт - timedeltaабо- None, якщо інформація про літній час невідома.- Return - timedelta(0)if DST is not in effect. If DST is in effect, return the offset as a- timedeltaobject (see- utcoffset()for details). Note that DST offset, if applicable, has already been added to the UTC offset returned by- utcoffset(), so there’s no need to consult- dst()unless you’re interested in obtaining DST info separately. For example,- datetime.timetuple()calls its- tzinfoattribute’s- dst()method to determine how the- tm_isdstflag should be set, and- tzinfo.fromutc()calls- dst()to account for DST changes when crossing time zones.- Екземпляр tz підкласу - tzinfo, який моделює як стандартний, так і денний час, має бути послідовним у цьому сенсі:- tz.utcoffset(dt) - tz.dst(dt)- must return the same result for every - datetimedt with- dt.tzinfo == tz. For sane- tzinfosubclasses, this expression yields the time zone’s «standard offset», which should not depend on the date or the time, but only on geographic location. The implementation of- datetime.astimezone()relies on this, but cannot detect violations; it’s the programmer’s responsibility to ensure it. If a- tzinfosubclass cannot guarantee this, it may be able to override the default implementation of- tzinfo.fromutc()to work correctly with- astimezone()regardless.- Більшість реалізацій - dst(), ймовірно, виглядатимуть як одна з цих двох:- def dst(self, dt): # a fixed-offset class: doesn't account for DST return timedelta(0) - або: - def dst(self, dt): # Code to set dston and dstoff to the time zone's DST # transition times based on the input dt.year, and expressed # in standard local time. if dston <= dt.replace(tzinfo=None) < dstoff: return timedelta(hours=1) else: return timedelta(0) - Стандартна реалізація - dst()викликає- NotImplementedError.- Змінено в версії 3.7: Зміщення літнього часу не обмежується цілою кількістю хвилин. 
- tzinfo.tzname(dt)¶
- Return the time zone name corresponding to the - datetimeobject dt, as a string. Nothing about string names is defined by the- datetimemodule, and there’s no requirement that it mean anything in particular. For example,- "GMT",- "UTC",- "-500",- "-5:00",- "EDT",- "US/Eastern",- "America/New York"are all valid replies. Return- Noneif a string name isn’t known. Note that this is a method rather than a fixed string primarily because some- tzinfosubclasses will wish to return different names depending on the specific value of dt passed, especially if the- tzinfoclass is accounting for daylight time.- Стандартна реалізація - tzname()викликає- NotImplementedError.
Ці методи викликаються об’єктом datetime або time у відповідь на їх однойменні методи. Об’єкт datetime передає себе як аргумент, а об’єкт time передає None як аргумент. Таким чином, методи підкласу tzinfo повинні бути готові прийняти аргумент dt None або клас datetime.
Коли передається None, розробник класу вирішує найкращу відповідь. Наприклад, повернення None є доцільним, якщо клас хоче сказати, що об’єкти часу не беруть участі в протоколах tzinfo. Може бути кориснішим для utcoffset(None) повертати стандартне зміщення UTC, оскільки немає іншої угоди для виявлення стандартного зсуву.
When a datetime object is passed in response to a datetime
method, dt.tzinfo is the same object as self. tzinfo methods can
rely on this, unless user code calls tzinfo methods directly. The
intent is that the tzinfo methods interpret dt as being in local
time, and not need worry about objects in other time zones.
Є ще один метод tzinfo, який підклас може захотіти перевизначити:
- tzinfo.fromutc(dt)¶
- This is called from the default - datetime.astimezone()implementation. When called from that,- dt.tzinfois self, and dt’s date and time data are to be viewed as expressing a UTC time. The purpose of- fromutc()is to adjust the date and time data, returning an equivalent datetime in self’s local time.- Most - tzinfosubclasses should be able to inherit the default- fromutc()implementation without problems. It’s strong enough to handle fixed-offset time zones, and time zones accounting for both standard and daylight time, and the latter even if the DST transition times differ in different years. An example of a time zone the default- fromutc()implementation may not handle correctly in all cases is one where the standard offset (from UTC) depends on the specific date and time passed, which can happen for political reasons. The default implementations of- astimezone()and- fromutc()may not produce the result you want if the result is one of the hours straddling the moment the standard offset changes.- Пропускаючи код для випадків помилки, реалізація за замовчуванням - fromutc()діє як:- def fromutc(self, dt): # raise ValueError error if dt.tzinfo is not self dtoff = dt.utcoffset() dtdst = dt.dst() # raise ValueError if dtoff is None or dtdst is None delta = dtoff - dtdst # this is self's standard offset if delta: dt += delta # convert to standard local time dtdst = dt.dst() # raise ValueError if dtdst is None if dtdst: return dt + dtdst else: return dt 
У наступному файлі tzinfo_examples.py є кілька прикладів класів tzinfo:
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
SECOND = timedelta(seconds=1)
# A class capturing the platform's idea of local time.
# (May result in wrong values on historical times in
#  timezones where UTC offset and/or the DST rules had
#  changed in the past.)
import time as _time
STDOFFSET = timedelta(seconds = -_time.timezone)
if _time.daylight:
    DSTOFFSET = timedelta(seconds = -_time.altzone)
else:
    DSTOFFSET = STDOFFSET
DSTDIFF = DSTOFFSET - STDOFFSET
class LocalTimezone(tzinfo):
    def fromutc(self, dt):
        assert dt.tzinfo is self
        stamp = (dt - datetime(1970, 1, 1, tzinfo=self)) // SECOND
        args = _time.localtime(stamp)[:6]
        dst_diff = DSTDIFF // SECOND
        # Detect fold
        fold = (args == _time.localtime(stamp - dst_diff))
        return datetime(*args, microsecond=dt.microsecond,
                        tzinfo=self, fold=fold)
    def utcoffset(self, dt):
        if self._isdst(dt):
            return DSTOFFSET
        else:
            return STDOFFSET
    def dst(self, dt):
        if self._isdst(dt):
            return DSTDIFF
        else:
            return ZERO
    def tzname(self, dt):
        return _time.tzname[self._isdst(dt)]
    def _isdst(self, dt):
        tt = (dt.year, dt.month, dt.day,
              dt.hour, dt.minute, dt.second,
              dt.weekday(), 0, 0)
        stamp = _time.mktime(tt)
        tt = _time.localtime(stamp)
        return tt.tm_isdst > 0
Local = LocalTimezone()
# A complete implementation of current DST rules for major US time zones.
def first_sunday_on_or_after(dt):
    days_to_go = 6 - dt.weekday()
    if days_to_go:
        dt += timedelta(days_to_go)
    return dt
# US DST Rules
#
# This is a simplified (i.e., wrong for a few cases) set of rules for US
# DST start and end times. For a complete and up-to-date set of DST rules
# and timezone definitions, visit the Olson Database (or try pytz):
# http://www.twinsun.com/tz/tz-link.htm
# https://sourceforge.net/projects/pytz/ (might not be up-to-date)
#
# In the US, since 2007, DST starts at 2am (standard time) on the second
# Sunday in March, which is the first Sunday on or after Mar 8.
DSTSTART_2007 = datetime(1, 3, 8, 2)
# and ends at 2am (DST time) on the first Sunday of Nov.
DSTEND_2007 = datetime(1, 11, 1, 2)
# From 1987 to 2006, DST used to start at 2am (standard time) on the first
# Sunday in April and to end at 2am (DST time) on the last
# Sunday of October, which is the first Sunday on or after Oct 25.
DSTSTART_1987_2006 = datetime(1, 4, 1, 2)
DSTEND_1987_2006 = datetime(1, 10, 25, 2)
# From 1967 to 1986, DST used to start at 2am (standard time) on the last
# Sunday in April (the one on or after April 24) and to end at 2am (DST time)
# on the last Sunday of October, which is the first Sunday
# on or after Oct 25.
DSTSTART_1967_1986 = datetime(1, 4, 24, 2)
DSTEND_1967_1986 = DSTEND_1987_2006
def us_dst_range(year):
    # Find start and end times for US DST. For years before 1967, return
    # start = end for no DST.
    if 2006 < year:
        dststart, dstend = DSTSTART_2007, DSTEND_2007
    elif 1986 < year < 2007:
        dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006
    elif 1966 < year < 1987:
        dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986
    else:
        return (datetime(year, 1, 1), ) * 2
    start = first_sunday_on_or_after(dststart.replace(year=year))
    end = first_sunday_on_or_after(dstend.replace(year=year))
    return start, end
class USTimeZone(tzinfo):
    def __init__(self, hours, reprname, stdname, dstname):
        self.stdoffset = timedelta(hours=hours)
        self.reprname = reprname
        self.stdname = stdname
        self.dstname = dstname
    def __repr__(self):
        return self.reprname
    def tzname(self, dt):
        if self.dst(dt):
            return self.dstname
        else:
            return self.stdname
    def utcoffset(self, dt):
        return self.stdoffset + self.dst(dt)
    def dst(self, dt):
        if dt is None or dt.tzinfo is None:
            # An exception may be sensible here, in one or both cases.
            # It depends on how you want to treat them.  The default
            # fromutc() implementation (called by the default astimezone()
            # implementation) passes a datetime with dt.tzinfo is self.
            return ZERO
        assert dt.tzinfo is self
        start, end = us_dst_range(dt.year)
        # Can't compare naive to aware objects, so strip the timezone from
        # dt first.
        dt = dt.replace(tzinfo=None)
        if start + HOUR <= dt < end - HOUR:
            # DST is in effect.
            return HOUR
        if end - HOUR <= dt < end:
            # Fold (an ambiguous hour): use dt.fold to disambiguate.
            return ZERO if dt.fold else HOUR
        if start <= dt < start + HOUR:
            # Gap (a non-existent hour): reverse the fold rule.
            return HOUR if dt.fold else ZERO
        # DST is off.
        return ZERO
    def fromutc(self, dt):
        assert dt.tzinfo is self
        start, end = us_dst_range(dt.year)
        start = start.replace(tzinfo=self)
        end = end.replace(tzinfo=self)
        std_time = dt + self.stdoffset
        dst_time = std_time + HOUR
        if end <= dst_time < end + HOUR:
            # Repeated hour
            return std_time.replace(fold=1)
        if std_time < start or dst_time >= end:
            # Standard time
            return std_time
        if start <= std_time < end - HOUR:
            # Daylight saving time
            return dst_time
Eastern  = USTimeZone(-5, "Eastern",  "EST", "EDT")
Central  = USTimeZone(-6, "Central",  "CST", "CDT")
Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
Pacific  = USTimeZone(-8, "Pacific",  "PST", "PDT")
Зауважте, що є неминучі тонкощі двічі на рік у підкласі tzinfo, що враховує як стандартний, так і денний час, у точках переходу на літній час. Для конкретності розглянемо Східну США (UTC -0500), де EDT починається через хвилину після 1:59 (EST) у другу неділю березня та закінчується через хвилину після 1:59 (EST) у першу неділю листопада:
  UTC   3:MM  4:MM  5:MM  6:MM  7:MM  8:MM
  EST  22:MM 23:MM  0:MM  1:MM  2:MM  3:MM
  EDT  23:MM  0:MM  1:MM  2:MM  3:MM  4:MM
start  22:MM 23:MM  0:MM  1:MM  3:MM  4:MM
  end  23:MM  0:MM  1:MM  1:MM  2:MM  3:MM
Коли починається літній час (рядок «початок»), місцевий настінний годинник переходить з 1:59 на 3:00. Настінний час у формі 2:MM насправді не має сенсу в цей день, тому astimezone(Eastern) не надасть результат з hour == 2 у день початку літнього часу. Наприклад, під час весняного переходу вперед 2016 року ми отримуємо:
>>> from datetime import datetime, timezone
>>> from tzinfo_examples import HOUR, Eastern
>>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
>>> for i in range(4):
...     u = u0 + i*HOUR
...     t = u.astimezone(Eastern)
...     print(u.time(), 'UTC =', t.time(), t.tzname())
...
05:00:00 UTC = 00:00:00 EST
06:00:00 UTC = 01:00:00 EST
07:00:00 UTC = 03:00:00 EDT
08:00:00 UTC = 04:00:00 EDT
When DST ends (the «end» line), there’s a potentially worse problem: there’s an
hour that can’t be spelled unambiguously in local wall time: the last hour of
daylight time. In Eastern, that’s times of the form 5:MM UTC on the day
daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
astimezone() mimics the local clock’s behavior by mapping two adjacent UTC
hours into the same local hour then. In the Eastern example, UTC times of the
form 5:MM and 6:MM both map to 1:MM when converted to Eastern, but earlier times
have the fold attribute set to 0 and the later times have it set to 1.
For example, at the Fall back transition of 2016, we get:
>>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
>>> for i in range(4):
...     u = u0 + i*HOUR
...     t = u.astimezone(Eastern)
...     print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
...
04:00:00 UTC = 00:00:00 EDT 0
05:00:00 UTC = 01:00:00 EDT 0
06:00:00 UTC = 01:00:00 EST 1
07:00:00 UTC = 02:00:00 EST 0
Note that the datetime instances that differ only by the value of the
fold attribute are considered equal in comparisons.
Applications that can’t bear wall-time ambiguities should explicitly check the
value of the fold attribute or avoid using hybrid
tzinfo subclasses; there are no ambiguities when using timezone,
or any other fixed-offset tzinfo subclass (such as a class representing
only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
Дивись також
zoneinfo
The
datetimemodule has a basictimezoneclass (for handling arbitrary fixed offsets from UTC) and itstimezone.utcattribute (a UTCtimezoneinstance).
zoneinfobrings the IANA time zone database (also known as the Olson database) to Python, and its usage is recommended.
- IANA time zone database
- База даних часових поясів (часто називається tz, tzdata або zoneinfo) містить код і дані, які представляють історію місцевого часу для багатьох репрезентативних місць у всьому світі. Він періодично оновлюється, щоб відобразити зміни, внесені політичними органами в межі часових поясів, зміщення UTC і правила переходу на літній час. 
timezone Об’єкти¶
The timezone class is a subclass of tzinfo, each
instance of which represents a time zone defined by a fixed offset from
UTC.
Objects of this class cannot be used to represent time zone information in the locations where different offsets are used in different days of the year or where historical changes have been made to civil time.
- class datetime.timezone(offset, name=None)¶
- Аргумент offset має бути вказаний як об’єкт - timedelta, що представляє різницю між місцевим часом і UTC. Воно має бути між- -timedelta(hours=24)і- timedelta(hours=24), інакше- ValueErrorвикликається.- Аргумент name необов’язковий. Якщо вказано, це має бути рядок, який використовуватиметься як значення, яке повертає метод - datetime.tzname().- Added in version 3.2. - Змінено в версії 3.7: Зсув UTC не обмежений цілою кількістю хвилин. 
- timezone.utcoffset(dt)¶
- Повертає фіксоване значення, указане під час створення екземпляра - timezone.- Аргумент dt ігнорується. Повернене значення є екземпляром - timedelta, що дорівнює різниці між місцевим часом і UTC.- Змінено в версії 3.7: Зсув UTC не обмежений цілою кількістю хвилин. 
- timezone.tzname(dt)¶
- Повертає фіксоване значення, указане під час створення екземпляра - timezone.- Якщо name не вказано в конструкторі, ім’я, яке повертає - tzname(dt), генерується зі значення- offsetнаступним чином. Якщо offset дорівнює- timedelta(0), ім’я - «UTC», інакше це рядок у форматі- UTC±HH:MM, де ± є знаком- offset, HH і MM – це дві цифри- offset.hoursі- offset.minutesвідповідно.- Змінено в версії 3.6: Name generated from - offset=timedelta(0)is now plain- 'UTC', not- 'UTC+00:00'.
- timezone.dst(dt)¶
- Завжди повертає - None.
- timezone.fromutc(dt)¶
- Повернути - dt + offset. Аргумент dt має бути відомим екземпляром- datetimeіз значенням- tzinfoзначення- self.
Атрибути класу:
- timezone.utc¶
- The UTC time zone, - timezone(timedelta(0)).
strftime() and strptime() Behavior¶
Об’єкти date, datetime і time підтримують метод strftime(format) для створення рядка, що представляє час під контролем явного рядок форматування.
Conversely, the date.strptime(), datetime.strptime() and
time.strptime() class methods create an object from a string
representing the time and a corresponding format string.
The table below provides a high-level comparison of strftime()
versus strptime():
| 
 | 
 | |
|---|---|---|
| Використання | Перетворити об’єкт на рядок відповідно до заданого формату | Parse a string into an object given a corresponding format | 
| Тип методу | Метод екземпляра | Метод класу | 
| Підпис | 
 | 
 | 
strftime() and strptime() Format Codes¶
These methods accept format codes that can be used to parse and format dates:
>>> datetime.strptime('31/01/22 23:59:59.999999',
...                   '%d/%m/%y %H:%M:%S.%f')
datetime.datetime(2022, 1, 31, 23, 59, 59, 999999)
>>> _.strftime('%a %d %b %Y, %I:%M%p')
'Mon 31 Jan 2022, 11:59PM'
Нижче наведено список усіх кодів форматів, яких вимагає стандарт C 1989 року, і вони працюють на всіх платформах зі стандартною реалізацією C.
| Директива | Значення | приклад | Примітки | 
|---|---|---|---|
| 
 | День тижня як скорочена назва локалі. | Нд, Пн, …, Сб (en_US); Отже, Пн, …, Сб (de_DE) | (1) | 
| 
 | День тижня як повна назва локалі. | неділя, понеділок, …, субота (en_US); Sonntag, Montag, …,
Samstag (de_DE) | (1) | 
| 
 | День тижня як десяткове число, де 0 – неділя, а 6 – субота. | 0, 1, …, 6 | |
| 
 | День місяця як десяткове число з доповненням нуля. | 01, 02, …, 31 | (9) | 
| 
 | Місяць як скорочена назва локалі. | січ, лютий, …, грудень (en_US); січ, лютий, …, дек (de_DE) | (1) | 
| 
 | Місяць як повна назва локалі. | січень, лютий, …, грудень (en_US); січень, лютий, …, грудень (de_DE) | (1) | 
| 
 | Місяць як десяткове число з доповненням нуля. | 01, 02, …, 12 | (9) | 
| 
 | Рік без століття як десяткове число з доповненням нуля. | 00, 01, …, 99 | (9) | 
| 
 | Рік із століттям як десяткове число. | 0001, 0002, …, 2013, 2014, …, 9998, 9999 | (2) | 
| 
 | Година (24-годинний формат) як десяткове число з доповненням нуля. | 00, 01, …, 23 | (9) | 
| 
 | Година (12-годинний годинник) як десяткове число з доповненням нуля. | 01, 02, …, 12 | (9) | 
| 
 | Локальний еквівалент AM або PM. | AM, PM (en_US); am, pm (de_DE) | (1), (3) | 
| 
 | Хвилина як десяткове число з доповненням нуля. | 00, 01, …, 59 | (9) | 
| 
 | Секунда як десяткове число з доповненням нуля. | 00, 01, …, 59 | (4), (9) | 
| 
 | Мікросекунда як десяткове число, доповнене нулями до 6 цифр. | 000000, 000001, …, 999999 | (5) | 
| 
 | Зміщення UTC у формі  | (порожній), +0000, -0400, +1030, +063415, -030712.345216 | (6) | 
| 
 | Назва часового поясу (пустий рядок, якщо об’єкт наївний). | (пусто), UTC, GMT | (6) | 
| 
 | День року як десяткове число з доповненням нуля. | 001, 002, …, 366 | (9) | 
| 
 | Номер тижня року (неділя як перший день тижня) як десяткове число з доповненням нуля. Усі дні в новому році, що передують першій неділі, вважаються нульовим тижнем. | 00, 01, …, 53 | (7), (9) | 
| 
 | Номер тижня року (понеділок як перший день тижня) як десяткове число з доповненням нуля. Усі дні в новому році, що передують першому понеділку, вважаються нульовим тижнем. | 00, 01, …, 53 | (7), (9) | 
| 
 | Відповідне представлення дати та часу в локалі. | Tue Aug 16 21:30:00
1988 (en_US); 16 серпня 21:30:00 1988 (de_DE) | (1) | 
| 
 | Відповідне представлення дати в локалі. | 16.08.88 (немає); 16.08.1988 (en_US); 16.08.1988 (de_DE) | (1) | 
| 
 | Відповідне представлення часу локалі. | 21:30:00 (en_US); 21:30:00 (de_DE) | (1) | 
| 
 | Буквальний символ  | % | 
Для зручності включено кілька додаткових директив, які не вимагаються стандартом C89. Усі ці параметри відповідають значенням дати ISO 8601.
| Директива | Значення | приклад | Примітки | 
|---|---|---|---|
| 
 | Рік ISO 8601 із століттям, що представляє рік, який містить більшу частину тижня ISO ( | 0001, 0002, …, 2013, 2014, …, 9998, 9999 | (8) | 
| 
 | День тижня ISO 8601 як десяткове число, де 1 означає понеділок. | 1, 2, …, 7 | |
| 
 | ISO 8601 тиждень як десяткове число з понеділком як першим днем тижня. Тиждень 01 – це тиждень, що містить 4 січня. | 01, 02, …, 53 | (8), (9) | 
| 
 | UTC offset in the form
 | (empty), +00:00, -04:00, +10:30, +06:34:15, -03:07:12.345216 | (6) | 
These may not be available on all platforms when used with the strftime()
method. The ISO 8601 year and ISO 8601 week directives are not interchangeable
with the year and week number directives above. Calling strptime() with
incomplete or ambiguous ISO 8601 directives will raise a ValueError.
The full set of format codes supported varies across platforms, because Python
calls the platform C library’s strftime() function, and platform
variations are common. To see the full set of format codes supported on your
platform, consult the strftime(3) documentation. There are also
differences between platforms in handling of unsupported format specifiers.
Added in version 3.6: Додано %G, %u і %V.
Added in version 3.12: %:z was added.
Технічні деталі¶
Broadly speaking, d.strftime(fmt) acts like the time module’s
time.strftime(fmt, d.timetuple()) although not all objects support a
timetuple() method.
For the datetime.strptime() class method, the default value is
1900-01-01T00:00:00.000: any components not specified in the format string
will be pulled from the default value. [4]
Використання datetime.strptime(date_string, format) еквівалентно:
datetime(*(time.strptime(date_string, format)[0:6]))
except when the format includes sub-second components or time zone offset
information, which are supported in datetime.strptime but are discarded by
time.strptime.
For time objects, the format codes for year, month, and day should not
be used, as time objects have no such values. If they’re used anyway,
1900 is substituted for the year, and 1 for the month and day.
For date objects, the format codes for hours, minutes, seconds, and
microseconds should not be used, as date objects have no such
values. If they’re used anyway, 0 is substituted for them.
З тієї ж причини обробка рядків формату, що містять кодові точки Юнікоду, які не можуть бути представлені в наборі символів поточної локалі, також залежить від платформи. На деяких платформах такі кодові точки зберігаються недоторканими у виводі, тоді як на інших strftime може викликати UnicodeError або замість цього повертати порожній рядок.
Примітки:
- Because the format depends on the current locale, care should be taken when making assumptions about the output value. Field orderings will vary (for example, «month/day/year» versus «day/month/year»), and the output may contain non-ASCII characters. 
- The - strptime()method can parse years in the full [1, 9999] range, but years < 1000 must be zero-filled to 4-digit width.- Змінено в версії 3.2: In previous versions, - strftime()method was restricted to years >= 1900.- Змінено в версії 3.3: In version 3.2, - strftime()method was restricted to years >= 1000.
- When used with the - strptime()method, the- %pdirective only affects the output hour field if the- %Idirective is used to parse the hour.
- Unlike the - timemodule, the- datetimemodule does not support leap seconds.
- When used with the - strptime()method, the- %fdirective accepts from one to six digits and zero pads on the right.- %fis an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available).
- For a naive object, the - %z,- %:zand- %Zformat codes are replaced by empty strings.- Для обізнаного об’єкта: - %z
- utcoffset()is transformed into a string of the form- ±HHMM[SS[.ffffff]], where- HHis a 2-digit string giving the number of UTC offset hours,- MMis a 2-digit string giving the number of UTC offset minutes,- SSis a 2-digit string giving the number of UTC offset seconds and- ffffffis a 6-digit string giving the number of UTC offset microseconds. The- ffffffpart is omitted when the offset is a whole number of seconds and both the- ffffffand the- SSpart is omitted when the offset is a whole number of minutes. For example, if- utcoffset()returns- timedelta(hours=-3, minutes=-30),- %zis replaced with the string- '-0330'.
 - Змінено в версії 3.7: Зсув UTC не обмежений цілою кількістю хвилин. - Змінено в версії 3.7: When the - %zdirective is provided to the- strptime()method, the UTC offsets can have a colon as a separator between hours, minutes and seconds. For example,- '+01:00:00'will be parsed as an offset of one hour. In addition, providing- 'Z'is identical to- '+00:00'.- %:z
- Behaves exactly as - %z, but has a colon separator added between hours, minutes and seconds.
- %Z
- In - strftime(),- %Zis replaced by an empty string if- tzname()returns- None; otherwise- %Zis replaced by the returned value, which must be a string.- strptime()only accepts certain values for- %Z:- будь-яке значення в - time.tznameдля локалі вашої машини
- закодовані значення - UTCі- GMT
 - Тому хтось, хто живе в Японії, може мати дійсні значення - JST,- UTCі- GMT, але, ймовірно, не- EST. Це викличе- ValueErrorдля недійсних значень.
 - Змінено в версії 3.2: When the - %zdirective is provided to the- strptime()method, an aware- datetimeobject will be produced. The- tzinfoof the result will be set to a- timezoneinstance.
- When used with the - strptime()method,- %Uand- %Ware only used in calculations when the day of the week and the calendar year (- %Y) are specified.
- Similar to - %Uand- %W,- %Vis only used in calculations when the day of the week and the ISO year (- %G) are specified in a- strptime()format string. Also note that- %Gand- %Yare not interchangeable.
- When used with the - strptime()method, the leading zero is optional for formats- %d,- %m,- %H,- %I,- %M,- %S,- %j,- %U,- %W, and- %V. Format- %ydoes require a leading zero.
- When parsing a month and day using - strptime(), always include a year in the format. If the value you need to parse lacks a year, append an explicit dummy leap year. Otherwise your code will raise an exception when it encounters leap day because the default year used by the parser is not a leap year. Users run into this bug every four years…- >>> month_day = "02/29" >>> datetime.strptime(f"{month_day};1984", "%m/%d;%Y") # No leap year bug. datetime.datetime(1984, 2, 29, 0, 0) - Deprecated since version 3.13, will be removed in version 3.15: - strptime()calls using a format string containing a day of month without a year now emit a- DeprecationWarning. In 3.15 or later we may change this into an error or change the default year to a leap year. See gh-70647.
Виноски