2011-03-27 2 views
1

내 프로그램의 한 부분에서는 사용자가 날짜를 입력해야하며 사전에있는 각 제품에 대해이 날짜를 확인하여 제품이 도착한 날짜와 유효 기간이 일치하는지 확인해야합니다 제품이 사용자가 입력 한 날짜 이전 또는 이후에 만료됩니다.날짜에 추가하여 만기 날짜가 지난 경우 확인

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: 

날짜 저장 형식을 날짜 형식으로 변경해야한다는 것을 알고 있지만 어떻게해야할지 확신이 서지 않습니다. 주어진 조언을 주셔서 감사합니다. :)

답변

1

정확하게 이해한다면 "dd/mm/yyyy"형식의 날짜를 나타내는 문자열을 datetime 객체로 변환해야합니까?

그렇다면 방법을 사용해야합니다.

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

이 인쇄 : 예를 들어

http://www.tutorialspoint.com/python/time_strptime.htm

거의 모든 :

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

예. 그게 내가 시도한 것입니다. 사전에 저장된 날짜로 처리하려고 시도했지만 오류가 계속 발생합니다. AttributeError : '모듈'객체에 'strptime'속성이 없습니다. – Ash

+0

불행히도 'datetime' 모듈과'datetime' 클래스가 둘 다 있습니다. 그 모듈. AttributeError는 클래스가 아닌 모듈을 참조하기 때문에 발생합니다. 'datetime.datetime.strptime (...) '을 사용하여 모듈 대신 클래스에 액세스하십시오. – srgerg

1

datetime 객체로 날짜 문자열을 구문 분석하기 위해, 당신은 strptime 방법을 사용할 수 있습니다 파이썬에 대해 알아야 할 것이 문서에서 찾을 수 있습니다. 여기 datetime의 문서이다

http://docs.python.org/library/datetime.html

수학 기간 (가감)에 관해서는, 이들은 추가하거나 datetime 객체 내지/A timedelta 객체를 감산함으로써 수행 될 수있다. 다음은 허용되는 작업입니다.

datetime2 = datetime1 + timedelta 
datetime2 = datetime1 - timedelta 
timedelta = datetime1 - datetime2 
datetime1 < datetime2 

자세한 내용은 위 링크의 설명서 페이지에서 확인할 수 있습니다.

http://phr0stbyte.blogspot.com/2008/08/python-datetime-math.html

0

내가 꽤 포괄적 인 객체 지향 재 작성했던 그것의 지옥의 경우 :

import datetime 

class Date(object): 
    def __init__(self, s): 
     if isinstance(s, Date): 
      self.date = s.date 
     elif isinstance(s, datetime.date): 
      self.date = s 
     else: 
      self.date = datetime.datetime.strptime(s, "%d/%m/%Y") 

    def __add__(self, val): 
     if isinstance(val, Life): 
      val = val.life 
     elif not isinstance(val, datetime.timedelta): 
      val = datetime.timedelta(val) 
     return self.__class__(self.date + val) 

    def __cmp__(self, val): 
     return (self.date - val.date).days 

    def __str__(self): 
     return self.date.strftime("%d/%m/%Y") 

class Life(object): 
    def __init__(self, s): 
     if isinstance(s, Life): 
      self.life = s.life 
     elif isinstance(s, datetime.timedelta): 
      self.life = s 
     else: 
      self.life = datetime.timedelta(days=int(s)) 

    def __str__(self): 
     return str(self.life.days) 

class Product(object): 
    FMT = "{0:10} {1:10} {2:24}".format 

    def __init__(self, date, life, name): 
     super(Product,self).__init__() 
     self.date = Date(date) 
     self.life = Life(life) 
     self.name = str(name).strip() 

    def __str__(self): 
     return Product.FMT(self.date, self.life, self.name) 

    def expires(self): 
     return Date(self.date + self.life) 

    @classmethod 
    def get(cls): 
     date = getClass(Date, "Please enter the date (DD/MM/YYYY): ") 
     life = getClass(Life, "Please enter the life (in days): ") 
     name = raw_input("Please enter the name of the cheese: ") 
     return cls(date, life, name) 

    def vals(self): 
     return self.date, self.life, self.name 

class FileOf(object): 
    def __init__(self, cls): 
     self.data = {} 
     self.cls = cls 

    def loadFile(self, fname, mode='r', sep=':'): 
     _data = self.data 
     _cls = self.cls 
     with open(fname, mode) as inf: 
      for line in inf: 
       try: 
        items = line.strip().split(sep) 
        id = items.pop(0) 
        _data[id] = _cls(*items) 
       except ValueError, e: 
        print(e) 
     return self 

    def saveFile(self, fname, mode='w', sep=':', eol='\n', key=None): 
     _data = self.data 
     keys = _data.keys() 
     keys.sort(key=key) 
     with open(fname, mode) as outf: 
      for id in keys: 
       outf.write(str(id)+sep) 
       outf.write(sep.join(str(v) for v in _data[id].vals())) 
       outf.write(eol) 
     return self 

    def addNew(self): 
     id = getNewKey(self.data, "Please enter the new ID: ") 
     obj = getClass(self.cls) 
     self.data[id] = obj 
     return self 

    def printAll(self, key=None): 
     _data = self.data 
     _cls = self.cls 
     ID = "{0:4} ".format 
     print ID("id") + _cls.FMT("Date", "Life", "Name") 
     keys = _data.keys() 
     keys.sort(key=key) 
     for id in keys: 
      print ID(id) + _cls.FMT(*(_data[id].vals())) 
     return self 

    def filter(self, filterFn): 
     newFile = FileOf(self.cls) 
     newFile.data = {id:item for id,item in self.data.iteritems() if filterFn(id, item)} 
     return newFile 

def getNewKey(keys, msg='', keytype=str): 
    "Prompt for a key not already in keys" 
    while True: 
     key = keytype(raw_input(msg)) 
     if key in keys: 
      print("This key already exists. Please try again.") 
     else: 
      return key 

def getClass(cls, *args, **kwargs): 
    "Return a new instance of given class; prompt for required values" 
    if hasattr(cls, 'get'): 
     # if the class knows how to 'get' itself, let it 
     return cls.get(*args, **kwargs) 
    else: 
     # otherwise we assume the class knows how to init itself from a string 
     while True: 
      s = raw_input(*args) 
      try: 
       return cls(s, **kwargs) 
      except ValueError, e: 
       print(e) 

def getExpired(cheeses, asOf=None):  
    asOf = Date(asOf) if asOf else getClass(Date, "Please enter expiration test date (DD/MM/YYYY): ") 
    return cheeses.filter(lambda id,obj: obj.expires() <= asOf) 

def main(): 
    cheeses = FileOf(Product).loadFile('cheesefile.txt') 
    cheeses.printAll() 

    cheeses.addNew() 

    expiredA = getExpired(cheeses)     # prompt for expiration date 
    expiredB = getExpired(cheeses, "12/3/2011") # use given date 

    print("The expired items are:") 
    expiredB.printAll() 

    cheeses.saveFile('cheesefile.txt') 

if __name__=="__main__": 
    main() 

및 샘플을

그리고 여기에는 날짜 수학에 또 다른 작은 튜토리얼 cheesefile.txt 파일 :

ab:03/01/2011:10:brie 
ac:03/01/2001:20:camembert 
de:01/03/2011:30:brie 
fg:01/03/2011:1:blink and it's gone 
hi:01/05/2011:200:hard white cheddar 
jkl:01/04/2011:60:jarlsberg 
관련 문제