Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Day name from Weekday int

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?

Here is the function I wrote, which works but I wanted something from the built in datetime lib.

def dayNameFromWeekday(weekday):     if weekday == 0:         return "Monday"     if weekday == 1:         return "Tuesday"     if weekday == 2:         return "Wednesday"     if weekday == 3:         return "Thursday"     if weekday == 4:         return "Friday"     if weekday == 5:         return "Saturday"     if weekday == 6:         return "Sunday" 
like image 999
GER Avatar asked Mar 31 '16 18:03

GER


People also ask

How do I get the day name in Python?

Use the strftime() method of a datetime module to get the day's name in English in Python. It uses some standard directives to represent a datetime in a string format. The %A directive returns the full name of the weekday. Like, Monday, Tuesday.

How do I print the day of a date in Python?

The strftime() method takes one or more format codes as an argument and returns a formatted string based on it. Here we will pass the directive “%A” in the method which provides Full weekday name for the given date.


Video Answer


1 Answers

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'] 
like image 121
dawg Avatar answered Oct 22 '22 17:10

dawg