我不明白日期时间
问题描述:
我试图使用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”))
我期待它是某种语法错误(这就是为什么我认为只需要发布该方法而不是整个脚本) 有人可以帮忙吗?
答
让我们来看看:
>>> 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'的文档吗?它需要三个参数。 –