Ali Hamza
Ali Hamza

Reputation: 131

how to get weekday from a given date in python?

2001-10-18 I want to calculate weekday e.g. Monday, Tuesday from the date given above. is it possible in python?

Upvotes: 6

Views: 26273

Answers (3)

Philip Evans
Philip Evans

Reputation: 1

Here's what I have that got me if a leap year and also days in a given month (accounts for leap years). Finding out a specific day of the week, that I'm also stuck on.

def is_year_leap(year):
    if (year & 4) == 0:
        return True
    if (year % 100) == 0:
        return False
    if (year % 400) == 0:
        return True
    return False

def days_in_month(year, month):
    if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
        return 31
    if month == 2:
        if is_year_leap(year):
            return 29
        else:
            return 28
    if month == 4 or month == 6 or month == 9 or month == 11:
        return 31

Upvotes: 0

Alix Eisenhardt
Alix Eisenhardt

Reputation: 313

There is the weekday() and isoweekday() methods for datetime objects.

Python doc

Upvotes: 6

Amit Wolfenfeld
Amit Wolfenfeld

Reputation: 623

Here is one way to do this:

dt = '2001-10-18'
year, month, day = (int(x) for x in dt.split('-'))    
answer = datetime.date(year, month, day).weekday()

Upvotes: 11

Related Questions