我不认识蒂姆

2024-06-28 19:43:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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给出了一个错误“TypeE”rror:an integer 是必需的(get type str)”

我这样称呼贷款: loan1=贷款(借款人1.name,BookCopy1.title,(“2016年6月22日”),(“2018年6月22日”))

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


Tags: 模块代码nameselfdatetimedatedefclass
1条回答
网友
1楼 · 发布于 2024-06-28 19:43:57

让我们看看:

>>> 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")

相关问题 更多 >