我的程序的一部分要求用户输入日期,然后根据字典中的每个产品检查此日期,以查看产品到达的日期以及保质期的原因该产品将在用户输入日期之前或之后过期。添加日期,检查过期是否过期
import sys
from string import *
import pickle
import datetime
cheeseDictionary = {}
userInput = ""
def loadProduct(fileName):
global cheeseDictionary
f = open(fileName,"r")
line = f.readline() # Reads line from file
while line:
line = line[:-1]
data = split(line,":") # Splits line when there is a colon
cheeseDictionary[data[0]] = {"date":data[1], "life":data[2], "name":data[3]} # Stores each split item
line = f.readline() # Next line
f.close()
def saveProduct(fileName,cheeseDictionary):
f = open(fileName, "w")
for i in sorted(cheeseDictionary.keys()):
v = cheeseDictionary[i]
f.write("%s:%s:%s:%s\n" % (i, v["date"], v["life"], v["name"]))
f.close()
def printProduct(cheeseDictionary):
print "ID"," ","Date"," ","Life(days)"," ","Name"
for cheese in cheeseDictionary:
print cheese," ",cheeseDictionary[cheese]["date"]," ",cheeseDictionary[cheese]["life"]," ",cheeseDictionary[cheese]["name"]
def addProduct():
global cheeseDicitonary
correct = 0
idInput = ""
dateInput = ""
lifeInput = ""
nameinput = ""
while correct != 1:
idInput = raw_input("Please enter the ID of the cheese to be added. ")
if cheeseDictionary.has_key(idInput):
print ("This ID already exists. Please try again.")
correct = 0
else:
newID = idInput
correct = 1
dateInput = raw_input("Please enter the date of the cheese to be added in the format dd/mm/yyyy. ")
lifeInput = raw_input("Please enter the life of the cheese to be added in days. ")
nameInput = raw_input("Please enter the name of the cheese to be added. ")
cheeseDictionary[idInput] = {"date":dateInput, "life":lifeInput, "name":nameInput}
def checkProduct(cheeseDictionary):
dateCheck = raw_input("Please enter the date in the format dd/mm/yyyy: ")
for cheese in cheeseDictionary:
我知道我需要更改日期商店嚣字典进入的日期时间格式,但我不确定如何做到这一点。感谢您提供的任何建议。 :)
是的,这是我一直在尝试做的。我试图用字典中存储的日期来做到这一点,但我不断收到错误:AttributeError:'module'object has no attribute'strptime' – Ash 2011-03-28 01:54:40
不幸的是,'datetime'模块和'datetime'类该模块。你得到的AttributeError是因为你引用了模块,而不是类。尝试使用'datetime.datetime.strptime(...)'来访问类而不是模块。 – srgerg 2011-03-28 02:29:46