Python date день недели

Python Get the Day of the Week

In this Python tutorial, I will show you exactly how to get the day of the week of a given date. For example, you want to find out the day’s name or number from the datetime.

In this datetime guide, I’ll cover:

  • weekday() method to get the day of the week as a number, where Monday is 0 and Sunday is 6.
  • isoweekday() method to get the weekday of a given date as an integer, where Monday is 1 and Sunday is 7.
  • strftime() method to get the name of the day from the date. Like Monday, Tuesday.
  • How to use the calendar module to get the name of the day from datetime.
  • Pandas Timestamp() method to get the number and name of the day.

Table of contents

How to Get the day of the week from datetime in Python

The below steps show how to use the datetime module’s weekday() method to get the day of a week as an integer number.

  1. Import datetime module Python datetime module provides various functions to create and manipulate the date and time. Use the from datetime import datetime statement to import a datetime class from a datetime module.
  2. Create datetime object The datetime module has a datetime class that contains the current local date and time. Use the now() method to get the current date and time. Or, If you have datetime in a string format, refer to converting a string into a datetime object.
  3. Use the weekday() method The weekday() method returns the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, the date(2022, 05, 02) is a Monday. So its weekday number is 0.
Читайте также:  Loader style loader css loader postcss loader

Example: Get the day of a week from Datetime

from datetime import datetime # get current datetime dt = datetime.now() print('Datetime is:', dt) # get day of week as an integer x = dt.weekday() print('Day of a week is:', x)
Datetime is: 2022-04-13 11:21:18.052308 Day of a week is: 2

The output is 2, equivalent to Wednesday as Monday is 0.

isoweekday() to get a weekday of a given date in Python

The weekday() method we used above returns the day of the week as an integer, where Monday is 0 and Sunday is 6.

Use the isoweekday() method to get the day of the week as an integer, where Monday is 1 and Sunday is 7. i.e., To start from the weekday number from 1, we can use isoweekday() in place of weekday() .

from datetime import datetime # get current datetime dt = datetime.now() print('Datetime is:', dt) print('Weekday is:', dt.isoweekday())
Datetime is: 2022-05-02 13:24:30.636135 Weekday is: 1

The output is 1, which is equivalent to Monday as Monday is 1.

Get a weekday where Sunday is 0

The strftime() approach If you’d like Sunday to be day 0

The strftime() uses some standard directives to convert a datetime into a string format. The same directives are shared between strptime() and strftime() methods.

The %w character code returns weekday as a decimal number, where 0 is Sunday, and 6 is Saturday.

from datetime import datetime # get current date d = datetime.now().date() # get weekday print(d.strftime('%w'))

Get the Weekday Name of a Date using strftime() method

In the above examples, we saw how to get the weekday of a date as an integer. In this section, let’s see how to get the day name of a given date ( such as Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday) from a datetime object in Python.

For example, datetime(2022, 5, 10, 8, 42, 10) should return me “Tuesday”.

Use the strftime() method of a datetime module to get the day’s name in English in Python. It uses some standard directives to represent a datetime in a string format. The %A directive returns the full name of the weekday. Like, Monday, Tuesday.

from datetime import datetime # get current datetime dt = datetime.now() print('Datetime is:', dt) # get weekday name print('day Name:', dt.strftime('%A'))
Datetime is: 2022-05-02 13:40:57.060953 day Name: Monday

Get the Weekday Name from date using Calendar Module

Python calendar module allows you to output calendars like the Unix cal program and provides additional useful functions related to the calendar.

The calendar.day_name method is used to get the name of the day from the date. This method contains an array that represents the days of the week in the current locale. Here, Monday is placed at index 0th index.

import calendar from datetime import date # get today's date d = date.today() print('Date is:', d) # get day name in english x = calendar.day_name[d.weekday()] print('Weekday name is:', x)
Date is: 2022-05-02 Weekday name is: Monday

Check if a date is a weekday or weekend

We can use the weekday() method of a datetime.date object to determine if the given date is a weekday or weekend.

Note: The weekday() method returns the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, the date(2022, 05, 02) is a Monday. So its weekday number is 0.

import datetime # given date x_date = datetime.date(2022, 4, 22) no = x_date.weekday() if no < 5: print("Date is Weekday") else: # 5 Sat, 6 Sun print("Date is Weekend")

Pandas Timestamp Method to Get the Name of the Day in Python

If you are working with a pandas series or dataframe, then the timestamp() method is helpful to get the day number and name.

  • First, pass the date in YYYY-MM-DD format as its parameter.
  • Next, use the dayofweek() and day_name() method to get the weekday number and name.
import pandas as pd d = pd.Timestamp('2022-05-02') print(d.dayofweek, d.day_name())

Summary

In this tutorial, we learned how to get the Name of the day in English and the day of the week as an integer number in Python.

  • Use the weekday() method to get the day of the week as an integer. In this method, Monday is 0 and Sunday is 6
  • If you want to start from 1, use the isoweekday() method. It returns the day of the week as an integer, where Monday is 1 and Sunday is 7.
  • Use the strftime() method or calendar module to get the name of the day in English. Like Monday, Tuesday.
  • Use Pandas Timestamp() method to get the number and name of the day.
from datetime import datetime import calendar # get current datetime dt = datetime.now() print('Datetime is:', dt) # weekday (Monday =0 Sunday=6) print('Weekday Number:', dt.weekday()) # isoweekday(Monday =1 Sunday=6) print('ISO Weekday Number:', dt.isoweekday()) # get weekday name print('Weekday Name:', dt.strftime('%A')) # get day name x = calendar.day_name[dt.weekday()] print('Weekday name is:', x)

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Модуль datetime

Python 3 логотип

Модуль datetime предоставляет классы для обработки времени и даты разными способами. Поддерживается и стандартный способ представления времени, однако больший упор сделан на простоту манипулирования датой, временем и их частями.

Классы, предоставляемые модулем datetime:

Класс datetime.date(year, month, day) - стандартная дата. Атрибуты: year, month, day. Неизменяемый объект.

Класс datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None) - стандартное время, не зависит от даты. Атрибуты: hour, minute, second, microsecond, tzinfo.

Класс datetime.timedelta - разница между двумя моментами времени, с точностью до микросекунд.

Класс datetime.tzinfo - абстрактный базовый класс для информации о временной зоне (например, для учета часового пояса и / или летнего времени).

Класс datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None) - комбинация даты и времени.

  • datetime.MINYEAR (1) ≤ year ≤ datetime.MAXYEAR (9999)
  • 1 ≤ month ≤ 12
  • 1 ≤ day ≤ количество дней в данном месяце и году

datetime.today() - объект datetime из текущей даты и времени. Работает также, как и datetime.now() со значением tz=None.

datetime.fromtimestamp(timestamp) - дата из стандартного представления времени.

datetime.fromordinal(ordinal) - дата из числа, представляющего собой количество дней, прошедших с 01.01.1970.

datetime.now(tz=None) - объект datetime из текущей даты и времени.

datetime.combine(date, time) - объект datetime из комбинации объектов date и time.

datetime.strptime(date_string, format) - преобразует строку в datetime (так же, как и функция strptime из модуля time).

datetime.strftime(format) - см. функцию strftime из модуля time.

datetime.date() - объект даты (с отсечением времени).

datetime.time() - объект времени (с отсечением даты).

datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]) - возвращает новый объект datetime с изменёнными атрибутами.

datetime.timetuple() - возвращает struct_time из datetime.

datetime.toordinal() - количество дней, прошедших с 01.01.1970.

datetime.timestamp() - возвращает время в секундах с начала эпохи.

datetime.weekday() - день недели в виде числа, понедельник - 0, воскресенье - 6.

datetime.isoweekday() - день недели в виде числа, понедельник - 1, воскресенье - 7.

datetime.isocalendar() - кортеж (год в формате ISO, ISO номер недели, ISO день недели).

datetime.isoformat(sep='T') - красивая строка вида "YYYY-MM-DDTHH:MM:SS.mmmmmm" или, если microsecond == 0, "YYYY-MM-DDTHH:MM:SS"

datetime.ctime() - см. ctime() из модуля time.

Пример работы с классом datetime:

Для вставки кода на Python в комментарий заключайте его в теги

  • Книги о Python
  • GUI (графический интерфейс пользователя)
  • Курсы Python
  • Модули
  • Новости мира Python
  • NumPy
  • Обработка данных
  • Основы программирования
  • Примеры программ
  • Типы данных в Python
  • Видео
  • Python для Web
  • Работа для Python-программистов

Источник

Оцените статью