2017-11-25 35 views
-6

我試圖使用datetime模塊和我永遠不能得到它的此代碼工作:我不明白日期時間

class Loan: 
    def __init__(self, person_name, bookLoaned, loanStart, loanEnd): 
     self.personName = person_name 
     self.bookLoaned = bookLoaned 
     self.loanStart = datetime.date(loanStart) 
     self.loanEnd = datetime.date(loanEnd) 

出於某種原因,PyScripter被給了一個錯誤「類型錯誤:一個整數是必需的(獲得類型str)「。

我拆款這樣的: loan1 =貸款(borrower1.name,BookCopy1.title,( 「22/06/2016」),( 「22/06/2018」))

我期待它是某種語法錯誤(這就是爲什麼我認爲只需要發佈該方法而不是整個腳本) 有人可以幫忙嗎?

+0

你怎麼叫'Loan'與 – user1767754

+1

開始什麼錯誤?請閱讀如何發佈[mcve]並適當編輯您的問題。你讀過'datetime.date'的文檔嗎?它需要三個參數。 –

回答

0

讓我們來看看:

>>> import datetime 
>>> help(datetime.date) 
Help on class date in module datetime: 

class date(builtins.object) 
| date(year, month, day) --> date object 
: 
>>> datetime.date(2016,6,22) 
datetime.date(2016, 6, 22) 

date並不需要一個字符串。縱觀help(datetime)strptime聽起來像你想要什麼:

>>> help(datetime.datetime.strptime) 
Help on built-in function strptime: 

strptime(...) method of builtins.type instance 
    string, format -> new datetime parsed from a string (like time.strptime()). 

此功能需要像你想要一個字符串,也是一種格式。讓我們來看看time.strptime不得不說的格式:

>>> import time 
>>> help(time.strptime) 
Help on built-in function strptime in module time: 

strptime(...) 
    strptime(string, format) -> struct_time 

    Parse a string to a time tuple according to a format specification. 
    See the library reference manual for formatting codes (same as 
    strftime()). 

    Commonly used format codes: 

    %Y Year with century as a decimal number. 
    %m Month as a decimal number [01,12]. 
    %d Day of the month as a decimal number [01,31]. 
    %H Hour (24-hour clock) as a decimal number [00,23]. 
    %M Minute as a decimal number [00,59]. 
    %S Second as a decimal number [00,61]. 
    %z Time zone offset from UTC. 
    %a Locale's abbreviated weekday name. 
    %A Locale's full weekday name. 
    %b Locale's abbreviated month name. 
    %B Locale's full month name. 
    %c Locale's appropriate date and time representation. 
    %I Hour (12-hour clock) as a decimal number [01,12]. 
    %p Locale's equivalent of either AM or PM. 

    Other codes may be available on your platform. See documentation for 
    the C library strftime function. 

所以一個datetime對象可以從一個字符串和一個合適的格式創建:

>>> datetime.datetime.strptime('22/06/2016','%d/%m/%Y') 
datetime.datetime(2016, 6, 22, 0, 0) 

,但你只想要一個date。回首幫助datetime.datetime,它有一個date()方法:

>>> datetime.datetime.strptime('22/06/2016','%d/%m/%Y').date() 
datetime.date(2016, 6, 22) 

爲您的代碼(作爲MCVE):

import datetime 

def date_from_string(strdate): 
    return datetime.datetime.strptime(strdate,'%d/%m/%Y').date() 

class Loan: 
    def __init__(self, person_name, bookLoaned, loanStart, loanEnd): 
     self.personName = person_name 
     self.bookLoaned = bookLoaned 
     self.loanStart = date_from_string(loanStart) 
     self.loanEnd = date_from_string(loanEnd) 

loan1 = Loan('John doe', 'Book Title', "22/06/2016", "22/06/2018")