讓我們來看看:
>>> 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")
你怎麼叫'Loan'與 – user1767754
開始什麼錯誤?請閱讀如何發佈[mcve]並適當編輯您的問題。你讀過'datetime.date'的文檔嗎?它需要三個參數。 –