Python DateTime weekday() Method with Example
Last Updated :
23 Aug, 2021
In this article, we will discuss the weekday() function in the DateTime module. weekday() function is used to get the week number based on given DateTime. It will return the number in the range of 0-6
Representation |
Meaning |
0 |
Monday |
1 |
Tuesday |
2 |
Wednesday |
3 |
Thursday |
4 |
Friday |
5 |
Saturday |
6 |
Sunday |
It will take input as DateTime in the format of “(YYYY, MM, DD, HH, MM, SS)”, where,
- YYYY stands for year
- MM stands for Month
- DD stands for Date
- HH stands for Hour
- MM stands for minute
- SS stands for second
We first need to import the DateTime module and create a DateTime, now using weekday() function we will get the weekday for a particular DateTime.
Syntax:
datetime(YYYY,MM,DD, HH,MM,SS).weekday()
we can also extract date from DateTime by using the following syntax:
Syntax:
datetime(YYYY,MM,DD, HH,MM,SS).date()
Example: Python program to create DateTime and display DateTime and date
Python3
from datetime import datetime
x = datetime( 2021 , 8 , 8 , 12 , 5 , 6 )
print ( "Datetime is :" , x)
print ( "Date is :" , x.date())
|
Output:
Datetime is : 2021-08-08 12:05:06
Date is : 2021-08-08
Example: Python program to get the weekdays for the given datetime(s)
Python3
from datetime import datetime
x = datetime( 2021 , 8 , 8 , 12 , 5 , 6 )
print ( "Datetime is :" , x)
print ( "weekday is :" , x.weekday())
x = datetime( 2021 , 9 , 10 , 12 , 5 , 6 )
print ( "Datetime is :" , x)
print ( "weekday is :" , x.weekday())
x = datetime( 2020 , 1 , 8 , 12 , 5 , 6 )
print ( "Datetime is :" , x)
print ( "weekday is :" , x.weekday())
|
Output:
Datetime is : 2021-08-08 12:05:06
weekday is : 6
Datetime is : 2021-09-10 12:05:06
weekday is : 4
Datetime is : 2020-01-08 12:05:06
weekday is : 2
Example 3: Python program to get the name of weekday
Python3
from datetime import datetime
days = [ "Monday" , "Tuesday" , "Wednesday" ,
"Thursday" , "Friday" , "Saturday" , "Sunday" ]
x = datetime( 2021 , 8 , 8 , 12 , 5 , 6 )
print ( "Datetime is :" , x)
print ( "weekday is :" , days[x.weekday()])
x = datetime( 2021 , 9 , 10 , 12 , 5 , 6 )
print ( "Datetime is :" , x)
print ( "weekday is :" , days[x.weekday()])
x = datetime( 2020 , 1 , 8 , 12 , 5 , 6 )
print ( "Datetime is :" , x)
print ( "weekday is :" , days[x.weekday()])
|
Output:
Datetime is : 2021-08-08 12:05:06
weekday is : Sunday
Datetime is : 2021-09-10 12:05:06
weekday is : Friday
Datetime is : 2020-01-08 12:05:06
weekday is : Wednesday
Share your thoughts in the comments
Please Login to comment...