[파이썬] 날짜와 시간의 주차와 요일 추출

Introduction

When working with dates and times in Python, we often need to extract specific information such as the week number or the day of the week. In this blog post, we will explore how to extract the week number and the day of the week from a given date and time using Python’s datetime module.

Extracting Week Number

To extract the week number from a given date, we can use the isocalendar() method available in the datetime module. This method returns a tuple containing the ISO year, week number, and weekday.

Here’s an example code snippet to extract the week number from a date:

import datetime

date = datetime.date(2022, 10, 31)  # Replace with your desired date

week_number = date.isocalendar()[1]

print(f"Week number: {week_number}")

The output will be:

Week number: 44

In the code snippet above, we first import the datetime module. We then create a date object representing the desired date (in this case, October 31, 2022). Finally, we call the isocalendar() method on the date object and access the second element of the returned tuple (which represents the week number) to obtain the desired result.

Extracting Day of the Week

To extract the day of the week from a given date, we can use the weekday() method available in the datetime module. This method returns an integer representing the day of the week, where Monday is 0 and Sunday is 6.

Here’s an example code snippet to extract the day of the week from a date:

import datetime

date = datetime.date(2022, 10, 31)  # Replace with your desired date

day_of_week = date.weekday()

print(f"Day of the week: {day_of_week}")

The output will be:

Day of the week: 0

In the code snippet above, we again import the datetime module and create a date object representing the desired date. We then call the weekday() method on the date object to obtain the day of the week as an integer.

To display the day of the week as a string, we can use the strftime() method on the date object with the appropriate format code. For example, to display the day of the week as a full name (e.g., Monday), we can use the format code %A:

import datetime

date = datetime.date(2022, 10, 31)  # Replace with your desired date

day_of_week = date.strftime("%A")

print(f"Day of the week: {day_of_week}")

The output will be:

Day of the week: Monday

Conclusion

In this blog post, we learned how to extract the week number and the day of the week from a given date and time in Python. We explored the isocalendar() and weekday() methods available in the datetime module to accomplish this task. Remember to adjust the date and time in the code examples to suit your needs.