Python Get Day Name from Number

Avatar
N

Nadia Chernoff

Python & Data Tooling Engineer••
8794Views
5mRead
0Reactions

In Python, there are numerous scenarios where you might need to convert a numeric representation of a day into its corresponding name. Whether you're working with date-related data or building applications that require day manipulation, Python provides efficient ways to accomplish this task. In this article, we'll explore how to get the day name from a number in Python, along with practical examples.

Using datetime Module

Python's datetime module simplifies date and time manipulation tasks, including retrieving day names from numbers. Here's how you can achieve this using the datetime module:

import datetime

def get_day_name(day_number):
    # Create a datetime object with any date and the given day number
    date_obj = datetime.datetime(2024, 2, day_number)
    # Return the full name of the day
    return date_obj.strftime("%A")

# Example usage:
day_number = 1  # Monday
day_name = get_day_name(day_number)
print(f"Day {day_number} is {day_name}")

Using calendar Module

Another approach involves utilizing Python's calendar module, which provides functionalities to work with calendars. Here's how you can leverage it to achieve the same result:

import calendar

def get_day_name(day_number):
    # Get the day name using the calendar module
    return calendar.day_name[day_number - 1]

# Example usage:
day_number = 3  # Wednesday
day_name = get_day_name(day_number)
print(f"Day {day_number} is {day_name}")

In this tutorial, we've explored two methods to get the day name from a number in Python. Whether you prefer the simplicity of the datetime module or the versatility of the calendar module, both approaches offer efficient solutions to this common programming challenge. By incorporating these techniques into your Python projects, you can effectively handle day-to-day date-related tasks with ease.

Connect with KoderSolution 🚀

Master modern software engineering, scalable architectures, and advanced backend systems.

What's your setup?What's your production setup for this scenario? Have you encountered similar architectural bottlenecks or edge-case gotchas?
Nadia Chernoff
N
Written by•Python & Data Tooling Engineer

Nadia Chernoff

Builds data extraction scripts, scrapers, and automated background sync workers. Uses Python scripts and background schedulers to automate repetitive dev chores.

React to this article

Recommended Articles

View all articles