Minh Đức Đặng
Minh Đức Đặng

Reputation: 1

Get the day of week given a date

I am working on my project on a timetable app. I can get the date with:

import datetime  
now = datetime.datetime.now()  
print (now.day, "/", now.month, "/", now.year)

But I can't get the day of the week though. Can someone help me?

Upvotes: 0

Views: 207

Answers (3)

prudent_programmer
prudent_programmer

Reputation: 11

There is an excellent answer by @seddonym on https://stackoverflow.com/a/29519293/4672536 to find the day of the week. I will post the code here for reference. Good luck! :) :

>>> from datetime import date
>>> import calendar
>>> my_date = date.today()
>>> calendar.day_name[my_date.weekday()]
'Wednesday'

Upvotes: 0

Giacomo Catenazzi
Giacomo Catenazzi

Reputation: 9523

To format and print dates, you should use the strftime functions (see the strftime python 3 documentation) instead of manually build your own format.

so e.g.

import datetime

now = datetime.datetime.now()
print(now.strftime("%A, %d/%m/%Y"))

Check out the doc, for the full list of styles. Maybe you want %a (abbreviated weekday name, or also %b or %B for the month name.

If you need just the values, check the datetime documenation, in the same page: you have now.weekday() (Monday is 0 and Sunday is 6), or now.iweekday() (Monday is 1 and Sunday is 7).

Upvotes: 2

Rajnil Guha
Rajnil Guha

Reputation: 435

Try this:

import time

localtime = time.localtime(time.time())
current_time = time.asctime(localtime)

print(current_time[:3])

This should work. Thanks.

Upvotes: 0

Related Questions