Python datetime get day number

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.
Читайте также:  Css grid cell width

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.

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.

Читайте также:  Php curl http client

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

Источник

Extract Day, Month & Year Separately from datetime Object in Python (3 Examples)

TikTok Icon Statistics Globe

In this article you’ll learn how to extract the day, month, and year separately from a datetime object in the Python programming language.

The table of content is structured as follows:

Let’s dive into the Python code!

Import datetime Module & Create Example Data

As a first step, we have to import the datetime module into Python:

from datetime import datetime

In this example, we’ll use the present datetime using the now() command:

print(datetime.now()) # 2021-11-19 06:59:44.221036

Let’s extract the day, month, and year from this datetime object!

Example 1: Extract Day from datetime Object

This example uses the day attribute to get the day of a datetime object:

Example 2: Extract Month from datetime Object

In this example we’ll extract the month number of the present datetime.

To achieve this, we can use the month attribute as shown below:

print(datetime.now().month) # 11

Example 3: Extract Year from datetime Object

This example uses the year attribute to return the year of the present datetime in 4-digit format:

print(datetime.now().year) # 2021

Video, Further Resources & Summary

Do you need more explanations on how to extract specific parts from a datetime object in Python? Then you should have a look at the following YouTube video of Corey Schafer’s YouTube channel.

In the video, the speaker explains how to use the datetime module in Python.

Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

If you accept this notice, your choice will be saved and the page will refresh.

accept

Accept YouTube Content

Furthermore, you could have a look at some of the other tutorials on Statistics Globe:

This post has shown how to return days, months, and years separately from a datetime object in the Python programming language. In case you have further questions, you may leave a comment below.

This tutorial was created in collaboration with Gottumukkala Sravan Kumar. Please have a look at Gottumukkala’s author page to get more information about his academic background and the other articles he has written for Statistics Globe.

Источник

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