首页 > 解决方案 > 如何使用日期时间库访问月份?

问题描述

以下是我的代码,可帮助我的学生在忘记密码时登录他们的帐户。今年的校历是 2019-2020 学年。如果我是五年级学生,我会在 2019 年进入学校。他们用户名的末尾使用他们高中毕业的年份。因此,我的代码是从当年开始加上 8 年来计算该数字。

然而这是问题所在,因为一个学年被新的一年分开,如果我的五年级学生输入 2020 年,他们将获得大 1 个整数的一年。

那么我将如何在我的代码中指定如果在一月和八月之间你需要从一年中减去 1,然后到 2020 年 9 月,新的五年级班级将使用 2020 作为他们的基础,因此他们的用户名中将有正确的数字.

import datetime
import sys

def find_info():
  first_name = input("What is your first name? ")
  sys.stdout.write("\033[F")
  sys.stdout.write("\033[K")

  last_name = input("What is your last name? ")
  sys.stdout.write("\033[F")
  sys.stdout.write("\033[K")

  grade = input("What grade are you in? ")
  sys.stdout.write("\033[F")
  sys.stdout.write("\033[K")

  year = datetime.date.today().year
  #month = datetime.date.today().month
  sys.stdout.write("\033[F")
  sys.stdout.write("\033[K")
  #This will only work in September of that year
  #If it passes January 1st of the school year the end number in username will be invalid
  #Need to come up with a way for a range of dates using if statement to ensure correct year

  pin = input("What is your lunch pin / ID number? ")
  sys.stdout.write("\033[F")
  sys.stdout.write("\033[K")

  #if month < :
  #  year -1

  grad_year = -1

  if grade == "5" or grade == str("5th") or grade == str("5TH") or grade == str("5th Grade") or grade == str("5th grade") or grade == str("5th GRADE") or grade == str("5TH GRADE"):
    grad_year = year + 8 
  elif grade == "6" or grade == str("6th") or grade == str("6TH"): 
    grad_year = year + 7
  elif grade == "7" or grade == str("7th") or grade == str("7TH"):
    grad_year = year + 6
  else:
    grad_year = year + 5

  print("Hello there " + first_name+"!") 
  print("\n")
  print("Your username is: " + last_name.lower() + first_name[0].lower() + str(grad_year)[2]+ str(grad_year)[3])
  print("Your password is: " + first_name[0].lower() + last_name[0].lower() + pin + "hoh")
  print("Your Email Address is: " + last_name.lower() + first_name[0].lower() + str(grad_year)[2]+ str(grad_year)[3] + "@learn.hohschools.org")

find_info()

标签: pythonpython-3.x

解决方案


datetime.date.today().month返回一个从 1 到 12 的整数,因此您可以检查该month值是否小于或等于 8 以检查月份是否在 1 月和 8 月之间。

  grad_year = 0

  if month <= 8:
    grad_year-= 1

  if grade == "5" or grade == str("5th") or grade == str("5TH"):
    grad_year = year + 8 
  ...

推荐阅读