Методы экземпляра ditetime.date() в python

Clock ID Constants¶

These constants are used as parameters for and
.

Identical to , except it also includes any time that
the system is suspended.

This allows applications to get a suspend-aware monotonic clock without
having to deal with the complications of , which may
have discontinuities if the time is changed using or
similar.

: Linux 2.6.39 or later.

New in version 3.7.

The Solaris OS has a timer that attempts to use an optimal
hardware source, and may give close to nanosecond resolution.
is the nonadjustable, high-resolution clock.

: Solaris.

New in version 3.3.

Clock that cannot be set and represents monotonic time since some unspecified
starting point.

: Unix.

New in version 3.3.

Similar to , but provides access to a raw
hardware-based time that is not subject to NTP adjustments.

: Linux 2.6.28 and newer, macOS 10.12 and newer.

New in version 3.3.

High-resolution per-process timer from the CPU.

: Unix.

New in version 3.3.

High-resolution per-process timer from the CPU.

: FreeBSD, NetBSD 7 or later, OpenBSD.

New in version 3.7.

The system must have a current leap second table in order for this to give
the correct answer. PTP or NTP software can maintain a leap second table.

: Linux.

New in version 3.9.

Thread-specific CPU-time clock.

: Unix.

New in version 3.3.

Time whose absolute value is the time the system has been running and not
suspended, providing accurate uptime measurement, both absolute and
interval.

: FreeBSD, OpenBSD 5.5 or later.

New in version 3.7.

Clock that increments monotonically, tracking the time since an arbitrary
point, unaffected by frequency or time adjustments and not incremented while
the system is asleep.

: macOS 10.12 and newer.

New in version 3.8.

The following constant is the only parameter that can be sent to
.

Методы экземпляра ditetime.date:

  • ,
  • ,
  • ,
  • ,
  • ,
  • ,
  • ,
  • ,
  • ,
  • .

Метод возвращает объект даты с тем же значением, за исключением тех параметров, которым даны новые значения в зависимости от того, какие ключевые аргументы указаны.

>>> import datetime
>>> date = datetime.date.today()
>>> date
# datetime.date(2020, 5, 5)
>>> date.replace(month=7, day=26)
# datetime.date(2020, 7, 26)

Метод возвращает объект структуры времени , например возвращенное функцией .

>>> import datetime
>>> date = datetime.date.today()
>>> date.timetuple()
# time.struct_time(tm_year=2020, tm_mon=5, tm_mday=5, 
#                  tm_hour=0, tm_min=0, tm_sec=0, 
#                  tm_wday=1, tm_yday=126, tm_isdst=-1)

Часы, минуты и секунды равны 0, а флаг DST равен -1. Метод эквивалентен следующему выражению :

time.struct_time((d.year, d.month, d.day, , , , d.weekday(), yday, -1))

где номер дня в текущем году, начиная с 1 для 1 января.

Метод возвращает григорианский порядковый номер даты, где 1 января 1 года имеет порядковый номер 1.

>>> import datetime
>>> date = datetime.date.today()
>>> date.toordinal()
# 737550

Метод возвращает день недели в виде целого числа, где понедельник равен 0, а воскресенье — 6.

>>> import datetime
>>> date = datetime.date.today()
>>> date.weekday()
# 1

Метод возвращает день недели в виде целого числа, где понедельник равен 0, а воскресенье — 6.

>>> import datetime
>>> date = datetime.date.today()
>>> date.isoweekday()
# 2

Метод возвращает тройной кортеж вида (год ISO, номер недели ISO, день недели ISO).

>>> import datetime
>>> date = datetime.date.today()
>>> date.isoweekday()
# (2020, 19, 2)

Календарь ISO является широко используемым вариантом григорианского календаря.

Год в ISO календаре состоит из 52 или 53 полных недель, где неделя начинается в понедельник и заканчивается в воскресенье. Первая неделя года ISO — это первая (григорианская) календарная неделя года, содержащая четверг. Это называется неделя № 1 и год ISO этого четверга совпадает с его григорианским годом.

Например, 2021 год начинается в пятницу, а первая неделя ISO 2021 года начинается в понедельник, т.е. 4 января 2020 года и заканчивается в воскресенье 10 января 2021 года:

>>> import datetime
>>> datetime.date(2021, 1, 4).isocalendar()
(2021, 1, 1)
>>> datetime.date(2021, 1, 10).isocalendar()
(2021, 1, 7)

Метод возвращает строку, представляющую дату в формате ISO 8601 :

>>> import datetime
>>> datetime.date.today().isoformat()
# '2020-05-05'
>>> date = datetime.date(2021, 12, 4).isoformat()
# '2021-12-04'

Это обратное значение .

Метод для объекта даты справедливо утверждение: str(date) эквивалентна .

>>> import datetime
>>> date = datetime.date.today()
>>> str(date)
# '2020-05-05'
>>> date = datetime.date(2021, 12, 4)
>>> date.__str__()
# '2021-12-04'

Метод возвращает строку, представляющую дату:

>>> import datetime
>>> date = datetime.date.today()
>>> date.ctime()
# 'Tue May  5 00:00:00 2020'
>>> datetime.date(2021, 12, 4).ctime()
# 'Sat Dec  4 00:00:00 2021'

Метод эквивалентен выражению:

time.ctime(time.mktime(data.timetuple()))

Метод возвращает строку, представляющую дату, которую задают явной строкой формата.

Коды формата, относящиеся к часам, минутам или секундам, будут отображать значение 0. Полный список директив форматирования смотрите в разделе «Поведение методов и модуля «.

Python strptime()

Python strptime() is a class method in datetime class. Its syntax is:

Both the arguments are mandatory and should be string. This function is exactly opposite of strftime() function, which converts datetime object to a string.

We have the similar function available in time module too, where its syntax is:

Here the function returns object. If format string is not provided, it defaults to “%a %b %d %H:%M:%S %Y” which matches the formatting returned by ctime() function.

If the input string cannot be parsed according to the provided format, then is raised. The exception message provides clear details about the issue in parsing.

time.sleep

Функция time.sleep дает разработчику возможность приостановить выполнение его скрипта на определенное количество секунд. Это можно сравнить с добавлением функции «Пауза» в вашу программу. Я нашел этот класс особенно полезным, когда мне нужно было подождать несколько секунд, пока закроется файл, или база данных закончит выполнять свою задачу. Давайте взглянем на пример. Откройте новое окно в IDLE и сохраните следующий код:

Python

import time

for x in range(5):
time.sleep(2)
print(«Slept for 2 seconds»)

1
2
3
4
5

importtime

forxinrange(5)

time.sleep(2)

print(«Slept for 2 seconds»)

Теперь запустите этот код в IDLE. Сделав это, вы увидите фразу «Slept for 2 seconds» пять раз, с интервалом в 2 секунды между каждым сообщением. Это очень легко в использовании!

Timezone Constants¶

The offset of the local DST timezone, in seconds west of UTC, if one is defined.
This is negative if the local DST timezone is east of UTC (as in Western Europe,
including the UK). Only use this if is nonzero. See note below.

Nonzero if a DST timezone is defined. See note below.

The offset of the local (non-DST) timezone, in seconds west of UTC (negative in
most of Western Europe, positive in the US, zero in the UK). See note below.

A tuple of two strings: the first is the name of the local non-DST timezone, the
second is the name of the local DST timezone. If no DST timezone is defined,
the second string should not be used. See note below.

Note

For the above Timezone constants (, , ,
and ), the value is determined by the timezone rules in effect
at module load time or the last time is called and may be incorrect
for times in the past. It is recommended to use the and
results from to obtain timezone information.

See also

Module

More object-oriented interface to dates and times.

Module

Internationalization services. The locale setting affects the interpretation
of many format specifiers in and .

Module

General calendar-related functions. is the
inverse of from this module.

Footnotes

The use of is now deprecated, but the escape that expands to the
preferred hour/minute offset is not supported by all ANSI C libraries. Also, a
strict reading of the original 1982 RFC 822 standard calls for a two-digit
year (%y rather than %Y), but practice moved to 4-digit years long before the
year 2000. After that, RFC 822 became obsolete and the 4-digit year has
been first recommended by RFC 1123 and then mandated by RFC 2822.

Приемы использования модуля datetime.

В этом разделе представлены частые приемы работы с объектом даты и времени .

  • ,
  • ,
  • ,
  • .
  • ,
  • ,
  • .
  • ,

Получаем текущее время и дату.

>>> import datetime
>>> dt = datetime.datetime.today()
>>> dt
# datetime.datetime(2020, 5, 5, 14, 56, 40, 902733)

# получаем отдельные компоненты
# даты 
>>> print(dt.year, dt.month, dt.day)
# 2020 5 5

# времени
>>> print(dt.hour, dt.minute, dt.second)
# 14 56 40

# Получаем объект даты
>>> dt.date()
# atetime.date(2020, 5, 5)

# Получаем объект времени
>>> dt.time()
# datetime.time(14, 56, 40, 902733)

Преобразуем объект в секунды ():

Задача: имеем объект , необходимо его преобразовать в секунды ().

>>> import datetime

# Для преобразования получим объект `datetime`, 
# содержащий дату и время в настоящий момент
>>> dt = datetime.datetime.now()
>>> dt  
# datetime.datetime(2020, 5, 6, 13, 52, 5, 208688)

# теперь получаем из `datetime` секунды - `timestamp` 
>>> second = dt.timestamp()
>>> second
# 1588762325.208688

# можно быстрее, одной строкой
>>> second = datetime.datetime.now().timestamp()
# 1588762325.208688

# если не нужны доли секунд, то 
# преобразуем в тип int
>>> int(second)
# 1588762325

Преобразуем время в секундах () в объект :

Задача: имеем время в секундах, необходимо из секунд получить объект , что бы потом что-то сделать.

>>> import datetime

# имеем время в секундах
second = 1588762325

# преобразовываем секунды в объект 'datetime'
# его же методом '.timestamp()'
>>> dt = datetime.datetime.fromtimestamp(second)
>>> dt
# datetime.datetime(2020, 5, 6, 13, 52, 5)

# дальше работаем как с объектом 
# получаем строку 
>>> dt.strfptint('%d.%m.%Y %H:%M')
# '06.05.2020 13:52'

# через сколько новый год
>>> future_dt = datetime.datetime.strptime('01.01.2021', '%d.%m.%Y')
>>> delta = future_dt - dt
# через дней
>>> delta.days
# 239

# секунд
>>> delta.seconds
# 36475

# месяцев
>>> 239 // 30
# 7

Получить объект из отдельных объектов и :

>>> import datetime 
# дата
>>> date = datetime.date.today()
# время
>>> time = datetime.time(23, 55)
# интервал
>>> delta = datetime.timedelta(minutes=30)
# соединяем все вместе
>>> datetime.datetime.combine(date, time) + delta
# datetime.datetime(2020, 5, 6, 0, 25)

Форматирование вывода строки c датой и временем:

Полный список директив форматирования смотрите в разделе «Коды форматирования и модуля «.

>>> import datetime
>>> dt = datetime.datetime.now()
>>> dt.strftime('%H:%M - %m.%d.%Y года')
# '09:56 - 05.06.2020 года'
>>> dt.strftime('%H часов %M минут %m.%d.%Y года')
# '09 часов 56 минут 05.06.2020 года'
>>> dt.strftime('%m/%d/%y')
# '05/06/20'
>>> dt.strftime('%Y-%m-%d')
# '2020-05-06'

# форматирование даты при помощи функции format()
>>> '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 06, the month is May, the time is 01:52PM.'

Преобразование строки с датой и временем в объект :

Полный список директив форматирования смотрите в разделе «Коды форматирования и модуля «.

>>> import datetime
>>> date_str = 'Fri, 24 Apr 2021 16:22:54 +0000'
>>> format = '%a, %d %b %Y %H:%M:%S +0000'
>>> datetime.datetime.strptime(date_str, format)
# datetime.datetime(2021, 4, 24, 16, 22, 54)

>>> date_str = '24.12.2020 16:22'
>>> format = '%d.%m.%Y %H:%M'
>>> datetime.datetime.strptime(date_str, format)
# datetime.datetime(2020, 12, 24, 16, 22)

Сложение и вычитание даты и времени:

При вычитании дат получается объект продолжительности —

Подсчет дней до события.

>>> import datetime
>>> today = datetime.datetime.now()
>>> date = datetime.datetime(2020, 12, 6)
>>> delta = date - today
>>> delta.days
# 213

Подсчет дней прошедших с события.

>>> import datetime
>>> date = datetime.datetime(2019, 12, 31)
>>> today = datetime.datetime.now()
>>> delta = today - date
>>> delta.days
# 127

Узнать дату и время предстоящего или прошедшего события.

>>> import datetime
>>> today = datetime.datetime.now()

# узнаем, какая дата будет через 3 недели и 5 дней 
>>> delta = datetime.timedelta(weeks=3, days=5)
>>> date = today + delta
>>> date.day, date.month, date.year
# (1, 6, 2020)

# узнаем, какая дата была 100 дней назад
>>> delta = datetime.timedelta(days=100)
>>> date = today - delta
>>> date.day, date.month, date.year
# (27, 1, 2020)

# узнаем, сколько время будет через 1 час 30 минут и 45 секунд
>>> delta = datetime.timedelta(hours=1, minutes=30, seconds=45)
>>> date = today + delta
>>> date.hour, date.minute, date.second
# (16, 18, 15)

Сравнение объектов :

  • datetime1 считается меньше datetime2, когда datetime1 предшествует datetime2 во времени
  • При сравнении c параметром не равным с , у которого параметром вызывается .
  • При сравнений на равенство c параметром не равным никогда не будут равен , у которого параметром .

The calendar Module

The calendar module supplies calendar-related functions, including functions to print a text calendar for a given month or year.

By default, calendar takes Monday as the first day of the week and Sunday as the last one. To change this, call calendar.setfirstweekday() function.

Here is a list of functions available with the calendar module −

Sr.No. Function with Description
1

calendar.calendar(year,w=2,l=1,c=6)

Returns a multiline string with a calendar for year year formatted into three columns separated by c spaces. w is the width in characters of each date; each line has length 21*w+18+2*c. l is the number of lines for each week.

2

calendar.firstweekday( )

Returns the current setting for the weekday that starts each week. By default, when calendar is first imported, this is 0, meaning Monday.

3

calendar.isleap(year)

Returns True if year is a leap year; otherwise, False.

4

calendar.leapdays(y1,y2)

Returns the total number of leap days in the years within range(y1,y2).

5

calendar.month(year,month,w=2,l=1)

Returns a multiline string with a calendar for month month of year year, one line per week plus two header lines. w is the width in characters of each date; each line has length 7*w+6. l is the number of lines for each week.

6

calendar.monthcalendar(year,month)

Returns a list of lists of ints. Each sublist denotes a week. Days outside month month of year year are set to 0; days within the month are set to their day-of-month, 1 and up.

7

calendar.monthrange(year,month)

Returns two integers. The first one is the code of the weekday for the first day of the month month in year year; the second one is the number of days in the month. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 to 12.

8

calendar.prcal(year,w=2,l=1,c=6)

Like print calendar.calendar(year,w,l,c).

9

calendar.prmonth(year,month,w=2,l=1)

Like print calendar.month(year,month,w,l).

10

calendar.setfirstweekday(weekday)

Sets the first day of each week to weekday code weekday. Weekday codes are 0 (Monday) to 6 (Sunday).

11

calendar.timegm(tupletime)

The inverse of time.gmtime: accepts a time instant in time-tuple form and returns the same instant as a floating-point number of seconds since the epoch.

12

calendar.weekday(year,month,day)

Returns the weekday code for the given date. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 (January) to 12 (December).

Clock ID Constants¶

These constants are used as parameters for and
.

Identical to , except it also includes any time that
the system is suspended.

This allows applications to get a suspend-aware monotonic clock without
having to deal with the complications of , which may
have discontinuities if the time is changed using or
similar.

: Linux 2.6.39 or later.

New in version 3.7.

The Solaris OS has a timer that attempts to use an optimal
hardware source, and may give close to nanosecond resolution.
is the nonadjustable, high-resolution clock.

: Solaris.

New in version 3.3.

Clock that cannot be set and represents monotonic time since some unspecified
starting point.

: Unix.

New in version 3.3.

Similar to , but provides access to a raw
hardware-based time that is not subject to NTP adjustments.

: Linux 2.6.28 and newer, macOS 10.12 and newer.

New in version 3.3.

High-resolution per-process timer from the CPU.

: Unix.

New in version 3.3.

High-resolution per-process timer from the CPU.

: FreeBSD, NetBSD 7 or later, OpenBSD.

New in version 3.7.

Thread-specific CPU-time clock.

: Unix.

New in version 3.3.

Time whose absolute value is the time the system has been running and not
suspended, providing accurate uptime measurement, both absolute and
interval.

: FreeBSD, OpenBSD 5.5 or later.

New in version 3.7.

The following constant is the only parameter that can be sent to
.

Format Code List

The table below shows all the format codes that you can use.

Directive Meaning Example
Abbreviated weekday name. Sun, Mon, …
Full weekday name. Sunday, Monday, …
Weekday as a decimal number. 0, 1, …, 6
Day of the month as a zero-padded decimal. 01, 02, …, 31
Day of the month as a decimal number. 1, 2, …, 30
Abbreviated month name. Jan, Feb, …, Dec
Full month name. January, February, …
Month as a zero-padded decimal number. 01, 02, …, 12
Month as a decimal number. 1, 2, …, 12
Year without century as a zero-padded decimal number. 00, 01, …, 99
Year without century as a decimal number. 0, 1, …, 99
Year with century as a decimal number. 2013, 2019 etc.
Hour (24-hour clock) as a zero-padded decimal number. 00, 01, …, 23
Hour (24-hour clock) as a decimal number. 0, 1, …, 23
Hour (12-hour clock) as a zero-padded decimal number. 01, 02, …, 12
Hour (12-hour clock) as a decimal number. 1, 2, … 12
Locale’s AM or PM. AM, PM
Minute as a zero-padded decimal number. 00, 01, …, 59
Minute as a decimal number. 0, 1, …, 59
Second as a zero-padded decimal number. 00, 01, …, 59
Second as a decimal number. 0, 1, …, 59
Microsecond as a decimal number, zero-padded on the left. 000000 — 999999
UTC offset in the form +HHMM or -HHMM.  
Time zone name.  
Day of the year as a zero-padded decimal number. 001, 002, …, 366
Day of the year as a decimal number. 1, 2, …, 366
Week number of the year (Sunday as the first day of the week). All days in a new year preceding the first Sunday are considered to be in week 0. 00, 01, …, 53
Week number of the year (Monday as the first day of the week). All days in a new year preceding the first Monday are considered to be in week 0. 00, 01, …, 53
Locale’s appropriate date and time representation. Mon Sep 30 07:06:05 2013
Locale’s appropriate date representation. 09/30/13
Locale’s appropriate time representation. 07:06:05
A literal ‘%’ character. %

ValueError in strptime()

If the string (first argument) and the format code (second argument) passed to the doesn’t match, you will get . For example:

If you run this program, you will get an error.

ValueError: time data '12/11/2018' does not match format '%d %m %Y'

Recommended Readings: Python strftime()

Python format datetime

The way date and time is represented may be different in different places, organizations etc. It’s more common to use in the US, whereas is more common in the UK.

Python has and methods to handle this.

Example 15: Format date using strftime()

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


time: 04:34:52
s1: 12/26/2018, 04:34:52
s2: 26/12/2018, 04:34:52

Here, , , , etc. are format codes. The method takes one or more format codes and returns a formatted string based on it.

In the above program, t, s1 and s2 are strings.

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

To learn more about and format codes, visit: Python strftime().

Example 16: strptime()

When you run the program, the output will be:


date_string = 21 June, 2018
date_object = 2018-06-21 00:00:00

The method takes two arguments:

  1. a string representing date and time
  2. format code equivalent to the first argument

By the way, , and format codes are used for day, month(full name) and year respectively.

Visit Python strptime() to learn more.

How to Use Date & DateTime Class

Step 1) Before you run the code for datetime, it is important that you import the date time modules as shown in the screenshot below.

These import statements are pre-defined pieces of functionality in the Python library that let you manipulates dates and times, without writing any code.

Consider the following points before executing the datetime code

from datetime import date

This line tells the Python interpreter that from the datetime module import the date class We are not writing the code for this date functionality alas just importing it for our use

Step 2) Next, we create an instance of the date object.

Step 3) Next, we print the date and run the code.

The output is as expected.

Модуль datetime

Модуль содержит классы:

Также существует класс , который применяется для работы с часовыми поясами.

Класс datetime.date

Класс принимает три аргумента: год, месяц и день.

>>> import datetime
>>> date = datetime.date(2017, 4, 2)
>>> date.year
2017
>>> date.month
4
>>> date.day
2

Давайте посмотрим, какой сейчас день:

>>> today = datetime.date.today()
>>> today.year
2018
>>> today.month
4
>>> today.day
21

Класс datetime.datetime

Класс принимает аргументы: год, месяц, день, час, минута, секунда и микросекунда.

>>> date_time = datetime.datetime(2017, 4, 21, 13, 30, 10)
>>> date_time.year
2017
>>> date_time.month
4
>>> date_time.day
21
>>> date_time.hour
13
>>> date_time.minute
30
>>> date_time.second
10

Давайте посмотрим, какое сейчас время:

>>> today = datetime.datetime.today()
>>> today
datetime.datetime(2018, 4, 21, 12, 43, 27, 786725)
>>> today.hour
12
>>> today.minute
43
>>> datetime.datetime.now() # местное время
datetime.datetime(2018, 4, 24, 13, 2, 39, 17479)
>>> datetime.datetime.utcnow() # время по Гринвичу
datetime.datetime(2018, 4, 24, 10, 2, 47, 46330)

Получить из объекта отдельно дату и отдельно время:

>>> today = datetime.datetime.today()
>>> today
datetime.datetime(2018, 4, 21, 13, 26, 54, 387462)
>>> today.date() # отдельно дата
datetime.date(2018, 4, 21)
>>> today.time() # отдельно время
datetime.time(13, 26, 54, 387462)

Классы и содержат метод , который позволяет создавать строку, отображающую время в более понятной для человека форме.

>>> today = datetime.date.today().strftime("%d.%m.%Y")
>>> today
'21.04.2018'
>>> import locale
>>> locale.setlocale(locale.LC_ALL, "ru") # задаем локаль для вывода даты на русском языке
'ru'
>>> today = datetime.datetime.today().strftime("%A, %d.%m.%Y")
>>> today
'суббота, 21.04.2018'
Сокращенное название дня недели
Полное название дня недели
Сокращенное название месяца
Полное название месяца
Дата и время
День месяца
24-часовой формат часа
12-часовой формат часа
День года. Цифровой формат
Номер месяца. Цифровой формат
Минута. Цифровой формат
До полудня или после (AM или PM)
Секунда. Цифровой формат
Номер недели в году. Цифровой формат (с воскресенья)
День недели. Цифровой формат
Номер недели в году. Цифровой формат (с понедельника)
Дата
Время
Год без века. Цифровой формат
Год с веком. Цифровой формат
Временная зона
Знак процента

Методы класса :

  • — объект из текущей даты и времени; работает также, как и со значением .
  • — объект из текущей даты и времени, местное время.
  • — объект из текущей даты и времени, по Гринвичу.
  • — дата из стандартного представления времени.
  • — дата из числа, представляющего собой количество дней, прошедших с 01.01.1970.
  • — объект из комбинации объектов и .
  • — преобразует строку в (так же, как и функция из модуля ).
  • — преобразует объект в строку согласно формату.
  • — объект даты (с отсечением времени).
  • — объект времени (с отсечением даты).
  • — возвращает новый объект с изменёнными атрибутами.
  • — возвращает из .
  • — количество дней, прошедших с 01.01.1970.
  • — возвращает время в секундах с начала эпохи Unix.
  • — день недели в виде числа, понедельник — 0, воскресенье — 6.
  • — день недели в виде числа, понедельник — 1, воскресенье — 7.
  • — кортеж (год в формате ISO, ISO номер недели, ISO день недели).
  • — красивая строка вида или, если ,
  • — возвращает строковое представление текущего местного времени.

Класс datetime.timedelta

Класс позволяет выполнять операции над датами — складывать, вычитать, сравнивать. Конструктор принимает именованные аргументы , , , , , , :

>>> delta = datetime.timedelta(days = 5, hours = 1, minutes = 1)
>>> delta
datetime.timedelta(5, 3660)

Интервал времени 5 дней, 1 час и 1 минута. Получить результат можно с помощью атрибутов , и (5 дней и 3660 секунд):

>>> delta.days
5
>>> delta.seconds
3660

Получить результат в секундах позволяет метод :

>>> today = datetime.datetime.today() # текущая дата
>>> today
datetime.datetime(2018, 4, 21, 15, 19, 2, 515432)
>>> future = datetime.datetime(2019, 4, 21, 15, 19, 2, 515432) # дата на один год больше
>>> delta = future - today
>>> delta
datetime.timedelta(365)
>>> delta.total_seconds() # 365 дней в секундах
31536000.0

Прибавить к текущей дате 10 дней, 10 часов и 10 минут:

>>> today = datetime.datetime.today()
>>> delta = datetime.timedelta(days = 10, hours = 10, minutes = 10)
>>> future = today + delta
>>> today # 21 апреля 2018 года, 15:29
datetime.datetime(2018, 4, 21, 15, 29, 29, 265954)
>>> future # 2 мая 2018 года, 01:39
datetime.datetime(2018, 5, 2, 1, 39, 29, 265954)

Операции с датами

Последнее обновление: 05.05.2017

Фоматирование дат и времени

Для форматирования объектов date и time в обоих этих классах предусмотрен метод strftime(format). Этот метод принимает только один
параметр, указывающий на формат, в который нужно преобразовать дату или время.

Для определения формата мы можем использовать один из следующих кодов форматирования:

  • %a: аббревиатура дня недели. Например, Wed — от слова Wednesday (по умолчанию используются английские наименования)

  • %A: день недели полностью, например, Wednesday

  • %b: аббревиатура названия месяца. Например, Oct (сокращение от October)

  • %B: название месяца полностью, например, October

  • %d: день месяца, дополненный нулем, например, 01

  • %m: номер месяца, дополненный нулем, например, 05

  • %y: год в виде 2-х чисел

  • %Y: год в виде 4-х чисел

  • %H: час в 24-х часовом формате, например, 13

  • %I: час в 12-ти часовом формате, например, 01

  • %M: минута

  • %S: секунда

  • %f: микросекунда

  • %p: указатель AM/PM

  • %c: дата и время, отформатированные под текущую локаль

  • %x: дата, отформатированная под текущую локаль

  • %X: время, форматированное под текущую локаль

Используем различные форматы:

from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d"))             # 2017-05-03
print(now.strftime("%d/%m/%Y"))             # 03/05/2017
print(now.strftime("%d/%m/%y"))             # 03/05/17
print(now.strftime("%d %B %Y (%A)"))        # 03 May 2017 (Wednesday)
print(now.strftime("%d/%m/%y %I:%M"))       # 03/05/17 01:36

При выводе названий месяцев и дней недели по умолчанию используются английские наименования. Если мы хотим использовать текущую локаль, но то мы
можем ее предварительно установить с помощью модуля locale:

from datetime import datetime
import locale
locale.setlocale(locale.LC_ALL, "")

now = datetime.now()
print(now.strftime("%d %B %Y (%A)"))        # 03 Май 2017 (среда)

Сложение и вычитани дат и времени

Нередко при работе с датами возникает необходимость добавить к какой-либо дате определенный промежуток времени или, наоборот, вычесть некоторый период. И специально для
таких операций в модуле datetime определен класс timedelta. Фактически этот класс определяет некоторый период времени.

Для определения промежутка времени можно использовать конструктор timedelta:

timedelta(      )

В конструктор мы последовательно передаем дни, секунды, микросекунды, миллисекунды, минуты, часы и недели.

Определим несколько периодов:

from datetime import timedelta

three_hours = timedelta(hours=3)
print(three_hours)       # 3:00:00
three_hours_thirty_minutes = timedelta(hours=3, minutes=30)  # 3:30:00

two_days = timedelta(2)  # 2 days, 0:00:00

two_days_three_hours_thirty_minutes = timedelta(days=2, hours=3, minutes=30)  # 2 days, 3:30:00

Используя timedelta, мы можем складывать или вычитать даты. Например, получим дату, которая будет через два дня:

from datetime import timedelta, datetime

now = datetime.now()
print(now)                      # 2017-05-03 17:46:44.558754
two_days = timedelta(2)
in_two_days = now + two_days
print(in_two_days)              # 2017-05-05 17:46:44.558754

Или узнаем, сколько было времени 10 часов 15 минут назад, то есть фактически нам надо вычесть из текущего времени 10 часов и 15 минут:

from datetime import timedelta, datetime

now = datetime.now()
till_ten_hours_fifteen_minutes = now - timedelta(hours=10, minutes=15)
print(till_ten_hours_fifteen_minutes) 

Свойства timedelta

Класс timedelta имеет несколько свойств, с помощью которых мы можем получить временной промежуток:

  • days: возвращает количество дней

  • seconds: возвращает количество секунд

  • microseconds: возвращает количество микросекунд

Кроме того, метод total_seconds() возвращает общее количество секунд, куда входят и дни, и собственно секунды, и микросекунды.

Например, узнаем какой временной период между двумя датами:

from datetime import timedelta, datetime

now = datetime.now()
twenty_two_may = datetime(2017, 5, 22)
period = twenty_two_may - now
print("{} дней  {} секунд   {} микросекунд".format(period.days, period.seconds, period.microseconds))
# 18 дней  17537 секунд   72765 микросекунд

print("Всего: {} секунд".format(period.total_seconds()))
# Всего: 1572737.072765 секунд

Сравнение дат

Также как и строки и числа, даты можно сравнивать с помощью стандартных операторов сравнения:

from datetime import datetime

now = datetime.now()
deadline = datetime(2017, 5, 22)
if now > deadline:
    print("Срок сдачи проекта прошел")
elif now.day == deadline.day and now.month == deadline.month and now.year == deadline.year:
    print("Срок сдачи проекта сегодня")
else:
    period = deadline - now
    print("Осталось {} дней".format(period.days))

НазадВперед

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

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