还是昨天书上那段示例代码,觉得可以发散思维下,写几句能让输入的数字自动计算并显示当前是周几,于是就写了下面这段代码:
- # 根据给定的年月日以数字形式打印出日期 并且自动输出当前日期是周几
- months = [
- 'January',
- 'February',
- 'March',
- 'April',
- 'May',
- 'June',
- 'July',
- 'August',
- 'September',
- 'October',
- 'November',
- 'December',
- ]
- # 以1~31的数字作为结尾的列表
- endings = ['st','nd','rd'] + 17 * ['th']\
- + ['st','nd','rd'] + 7 * ['th']\
- + ['st']
- # 定义‘周几’这个变量,通过日期可以自动显示当前日期是周几
- ending = [
- 'Tuesday',
- 'Wednesday',
- 'Thursday',
- 'Friday',
- 'Saturday',
- 'Sunday',
- 'Monday',
- 'Tuesday',
- 'Wednesday',
- 'Thursday',
- 'Friday',
- 'Saturday',
- 'Sunday',
- 'Monday',
- 'Tuesday',
- 'Wednesday',
- 'Thursday',
- 'Friday',
- 'Saturday',
- 'Sunday',
- 'Monday',
- 'Tuesday',
- 'Wednesday',
- 'Thursday',
- 'Friday',
- 'Saturday',
- 'Sunday',
- 'Monday',
- 'Tuesday',
- 'Wednesday',
- 'Thursday',
- ]
- year = raw_input('Year: ')
- month = raw_input('Month(1-12): ')
- day = raw_input('Day(1-31): ')
- month_number = int(month)
- day_number = int(day)
- # 记得要将月份和天数减1,以获得正确的索引
- month_name = months[month_number-1]
- ordinal = day + endings[day_number-1]
- week_name = ending[day_number-1]
- print month_name + ' ' + ordinal + ', ' + year + ' ' + week_name
- # 根据给定的年月日以数字形式打印出日期 并且自动输出当前日期是周几
- months = [
- 'January',
- 'February',
- 'March',
- 'April',
- 'May',
- 'June',
- 'July',
- 'August',
- 'September',
- 'October',
- 'November',
- 'December',
- ]
- # 以1~31的数字作为结尾的列表
- endings = ['st','nd','rd'] + 17 * ['th']\
- + ['st','nd','rd'] + 7 * ['th']\
- + ['st']
- # 定义‘周几’这个变量,通过日期可以自动显示当前日期是周几
- ending = [
- 'Tuesday',
- 'Wednesday',
- 'Thursday',
- 'Friday',
- 'Saturday',
- 'Sunday',
- 'Monday',
- ]
- year = raw_input('Year: ')
- month = raw_input('Month(1-12): ')
- day = raw_input('Day(1-31): ')
- month_number = int(month)
- day_number = int(day)
- # 记得要将月份和天数减1,以获得正确的索引
- month_name = months[month_number-1]
- ordinal = day + endings[day_number-1]
- week_name = ending[(day_number-1)%7]
- print month_name + ' ' + ordinal + ', ' + year + ' ' + week_name
补充: 网友提供的方法,目前还看不懂,留着以后研究
将用户输入的格式化 一下, 然后传入 datetime里面. 调用strftime方法 得到该日期的星期
datetime.datetime(2012,05,8).strftime("%w")
datetime.datetime(2012,05,13).strftime("%w").replace("0","7")