How to get day name from datetime

PythonDatetime

Python Problem Overview


How can I get the day name (such as Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday) from a datetime object in Python?

So, for example, datetime(2019, 9, 6, 11, 33, 0) should give me "Friday".

Python Solutions


Solution 1 - Python

import datetime
now = datetime.datetime.now()
print(now.strftime("%A"))

See the Python docs for datetime.now, datetime.strftime and more on strftime.

Solution 2 - Python

>>> from datetime import datetime as date
>>> date.today().strftime("%A")
'Monday'

Solution 3 - Python

If you don't mind using another package, you can also use pandas to achieve what you want:

>>> my_date = datetime.datetime(2019, 9, 6, 11, 33, 0)
>>> pd.to_datetime(my_date).day_name()
'Friday'

It does not sound like a good idea to use another package for such easy task, the advantage of it is that day_name method seems more understandable to me than strftime("%A") (you might easily forget what is the right directive for the format to get the day name).

Hopefully, this could be added to datetime package directly one day (e.g. my_date.day_name()).

Solution 4 - Python

import datetime
numdays = 7
base = datetime.date.today()
date_list = [base + datetime.timedelta(days=x) for x in range(numdays)]
date_list_with_dayname = ["%s, %s" % ((base + datetime.timedelta(days=x)).strftime("%A"),  base + datetime.timedelta(days=x)) for x in range(numdays)]

Solution 5 - Python

Alternative

You can use import time instead of datetime as following:

import time
WEEKDAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

now = time.localtime()
weekday_index = now.tm_wday
print(WEEKDAYS[weekday_index])

Solution 6 - Python

import datetime
now = datetime.datetime.now()
print(now.dt.day_name())

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongadssView Question on Stackoverflow
Solution 1 - PythonMatt JoinerView Answer on Stackoverflow
Solution 2 - PythonAbhijitView Answer on Stackoverflow
Solution 3 - PythonNerxisView Answer on Stackoverflow
Solution 4 - Pythonuser3769499View Answer on Stackoverflow
Solution 5 - PythonAppoView Answer on Stackoverflow
Solution 6 - PythonberkaylnView Answer on Stackoverflow