Day of week given a date

vegaseat 3 Tallied Votes 2K Views Share

So you want to find out which day of the week you were born. Well at least some of us do. I actually wrote this program because my whole family was born on Sundays, and my friends didn't believe it! An oldie but goodie, moved from DeSmet C to Turbo C, to Pelles C, and now to Python.

''' day_week_born.py
ask to enter a birthday and show the day of the week the person was born
some dates in history ...
July 4, 1776 was on a Thursday
December 7, 1941 was on a Sunday
3/14/1879 was on a Friday (Albert Einstein's birthday aka. pi-day)
tested with Python32/33  by  vegaseat  14feb2013
'''

import datetime as dt

while True:
    # stay in the loop until correct date is entered
    try:
        # for Python2 replace input() with raw_input()
        birthday_str = input("Enter birthday (format mm/dd/yyyy): ")
        m, d, y = birthday_str.split('/')
        birthday = dt.date(int(y), int(m), int(d))
        if int(y) > 1700:
            break
    except:
        print("Please enter correct date!")

week_day = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
  'Friday', 'Saturday', 'Sunday']

sf = "If you were born on %s, you were born on a %s"
print(sf % (birthday_str, week_day[dt.date.weekday(birthday)]))
TrustyTony 888 pyMod Team Colleague Featured Poster

Here is alternative format for the code:

''' day_week_born.py
ask to enter a birthday and show the day of the week the person was born
some dates in history ...
July 4, 1776 was on a Thursday
December 7, 1941 was on a Sunday
3/14/1879 was on a Friday (Albert Einstein's birthday aka. pi-day)
tested with Python32/33  by  vegaseat  14feb2013
Variation by pyTony 14feb2013
'''
# for Python2
try:
    input = raw_input
except:
    pass

import datetime as dt
def get_birthday():
    while True:
        try:
            birthday = dt.datetime.strptime(input("Enter birthday (format mm/dd/yyyy, after 1700): "), '%m/%d/%Y')
        except ValueError as v:
            print(v)
        else:
            if birthday.year > 1700:
                return birthday.weekday()

weekday = 'Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split()
print("You were born on a %s" % weekday[get_birthday()])
1baga 0 Newbie Poster

nice piece of code..i am sure i will learn python faster than i expected over here

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.