gpt4 book ai didi

python - 添加日期,检查是否已过期

转载 作者:行者123 更新时间:2023-12-01 06:11:55 26 4
gpt4 key购买 nike

我的程序的一部分要求用户输入一个日期,然后根据字典中的每个产品检查该日期,看看产品到达日期加上其保质期是否会导致产品在输入日期之前或之后过期由用户。

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:

我知道我需要将字典中存储的日期更改为日期时间格式,但我不确定如何执行此操作。感谢您提供的任何建议。 :)

最佳答案

如果我理解正确的话,您需要将表示“dd/mm/yyyy”格式的日期的字符串转换为日期时间对象?

如果是这样,您应该使用 datetime.strptime方法。例如:

from datetime import datetime
d = datetime.strptime("28/03/2011", "%d/%m/%Y")
print repr(d)

打印:

datetime.datetime(2011, 3, 28, 0, 0)

关于python - 添加日期,检查是否已过期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5453331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com