How to get Weekday as Number using Python datetime?

Python datetime – Get Weekday as Number

To get Weekday As a Number using Python datetime, call strftime() with %w passed as argument.

WeekdayOutput
Sunday0
Monday1
Tuesday2
Wednesday3
Thursday4
Friday5
Saturday6

Example 1: Get Weekday as Number of Current Date

In the following example, we will take the current date, and get weekday as number.

#import datetime package
import datetime

#get current time
d = datetime.datetime.now()

#print date
print(d)

#get the weekday as number
print(d.strftime("%w"))
Run this program ONLINE

Output

2019-06-26 08:14:39.077008
3

The week starts with Sunday as 0. Monday is 1. Hence Wednesday is 3.

Example 2: Get Weekday as Number of Specific Date

In the following example, we will take a date 2019-08-12 and get the weekday number.

#import datetime package
import datetime

#set a date
d = datetime.datetime(2019,8,12)

#print date
print(d)

#get the weekday as number
print(d.strftime("%w"))
Run this program ONLINE

Output

2019-08-12 00:00:00
1

2019-08-12 is a Monday. Hence the weekday (Monday) as number is 1.

Summary

In this tutorial, we extracted weekday from date as a number.