Search code examples
pythonnumbersweekday

How to convert a number to its correlating day of the week?


How do I convert a number to its correlating day of the week?

For example:

def string(hour_of_day, day_of_week, date) :
   print(f'{day_of_week} {date} at hour {hour_of_day}')

how can I re-write the 'day_of_week' part in print so that when I use the function:

string(12, 1, '2020/02/18') 

How can I get Tuesday 2020/02/18 at hour 12 instead of 1 2020/02/18 at hour 12?


Solution

  • Use calendar module

    If you have already the weekday number, do:

    import calendar
    
    day_of_week = 1
    calendar.day_name[day_of_week]
    ## 'Tuesday'
    

    The calendar module is always available in Python (it is belongs to the inbuilt standard modules).

    So the dictionary {0: "Monday", 1: "Tuesday", ...} is already defined as calendar.day_name. So no need to define it yourself. Instead type import calendar and you have it available.

    Use datetime module to get weekday directly from the date

    from datetime import datetime
    
    def date2weekday(date):
        return datetime.strptime(date, "%Y/%m/%d").strftime('%A')
    
    def myfunction(hour_of_day, date):
        return f"{date2weekday(date)} {date} at hour {hour_of_day}"
    
    myfunction(12, '2020/02/18') 
    ## 'Tuesday 2020/02/18 at hour 12'