How to get day name from datetime

Question:

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".

Asked By: gadss

||

Answers:

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

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

Answered By: Matt Joiner
>>> from datetime import datetime as date
>>> date.today().strftime("%A")
'Monday'
Answered By: Abhijit
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)]
Answered By: user3769499

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()).

Answered By: Nerxis

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])
Answered By: Appo

You can use an f-string along with a format code such as %A or %a:

> import datetime

# Provide a date object:
> d = datetime.date.today()
> d
datetime.date(2023, 2, 3)

# Provide a datetime object:
> dt = datetime.datetime.now()
> dt
datetime.datetime(2023, 2, 3, 17, 48, 7, 415010)

# Full weekday name:
> f'{d:%A}'
'Friday'
> f'{dt:%A}'
'Friday'

# Abbreviated weekday name:
> f'{d:%a}'
'Fri'
> f'{dt:%a}'
'Fri'

Note that the output strings are locale dependent. If requiring a locale independent comparison or even just a faster comparison, consider date.weekday() and datetime.weekday().

Answered By: Asclepius
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.