我没有获得约会时间

时间:2017-11-25 22:14:07

标签: python datetime

我正在尝试使用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给出了一个错误" TypeError:需要一个整数(得到类型str)"。

我这样称贷款:  loan1 =贷款(borrower1.name,BookCopy1.title,(" 22/06 / 2016"),(" 22/06/208"))

我希望它是某种语法错误(这就是为什么我认为只需要发布方法而不是整个脚本) 有人可以帮忙吗?

1 个答案:

答案 0 :(得分: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")