Get Day name from Weekday int

后端 未结 8 1117
梦如初夏
梦如初夏 2020-12-14 05:14

I have a weekday integer (0,1,2...) and I need to get the day name (\'Monday\', \'Tuesday\',...).

Is there a built in Python function or way of doing this?

H

相关标签:
8条回答
  • 2020-12-14 06:19

    It is more Pythonic to use the calendar module:

    >>> import calendar
    >>> list(calendar.day_name)
    ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    

    Or, you can use common day name abbreviations:

    >>> list(calendar.day_abbr)
    ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    

    Then index as you wish:

    >>> calendar.day_name[1]
    'Tuesday'
    

    (If Monday is not the first day of the week, use setfirstweekday to change it)

    Using the calendar module has the advantage of being location aware:

    >>> import locale
    >>> locale.setlocale(locale.LC_ALL, 'de_DE')
    'de_DE'
    >>> list(calendar.day_name)
    ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag']
    
    0 讨论(0)
  • 2020-12-14 06:20

    You could use a list which you get an item from based on your argument:

    def dayNameFromWeekday(weekday):
        days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
        return days[weekday]
    

    If you needed the function to not cause an error if you passed in an invalid number, for example "8", you could check if that item of the list exists before you return it:

    def dayNameFromWeekday(weekday):
        days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
        return days[weekday] if 0 < weekday < len(days) else None
    

    This function can be used like you'd expect:

    >>> dayNameFromWeekday(6)
    Sunday
    >>> print(dayNameFromWeekday(7))
    None
    

    I'm not sure there's a way to do this built into datetime, but this is still a very efficient way.

    0 讨论(0)
提交回复
热议问题