Write a Python program to get the current week


The Python program demonstrates two methods to get the ISO year, ISO week number, and day of the week from the current date and time. Here is a step-by-step explanation of the program:

  • import datetime: This line imports the built-in datetime module, which provides classes for working with dates and times.
  • dt = datetime.datetime.now(): This line creates a new datetime object that represents the current date and time, and assigns it to the variable dt.
  • year,week_num,day_of_week = dt.isocalendar(): This line uses the isocalendar() method of the datetime object to get the ISO year, ISO week number, and day of the week, and assigns them to the variables year, week_num, and day_of_week, respectively. The isocalendar() method returns a tuple of three values: the ISO year, the ISO week number, and the day of the week (1 for Monday, 2 for Tuesday, etc.).
  • print("Year %d, Week Number %d, Day of the Week %d" %(year,week_num, day_of_week)) : This line uses string formatting to display the ISO year, ISO week number, and day of the week on the console. The %d format specifier is used to format the integer values of the variables.
  • print("year : ", dt.strftime("%Y")): This line uses the strftime() method of the datetime object to get the year in the format of "YYYY":, and prints it on the console along with the message "year : ".
  • print("Week number of the year : ", dt.strftime("%W")): This line uses the strftime() method of the datetime object to get the week number of the year, and prints it on the console along with the message "Week number of the year : ".
  • print("Day of The week : ", dt.strftime("%w")): This line uses the strftime() method of the datetime object to get the day of the week as an integer (0 for Sunday, 1 for Monday, etc.), and prints it on the console along with the message "Day of The week : ".

Source Code

import datetime
import datetime
dt = datetime.datetime.now()
print("\n----------First Method----------\n")
year,week_num,day_of_week = dt.isocalendar()
print("Year %d, Week Number %d, Day of the Week %d" %(year,week_num, day_of_week))
 
print("\n----------Second Method----------\n")
print("year : ", dt.strftime("%Y"))
print("Week number of the year : ", dt.strftime("%W"))
print("Day of The week : ", dt.strftime("%w"))

Output

----------First Method----------

Year 2022, Week Number 38, Day of the Week 6

----------Second Method----------

year :  2022
Week number of the year :  38
Day of The week :  6

Example Programs