我有一个以下格式的文件

Summary:meeting Description:None DateStart:20100629T110000 DateEnd:20100629T120000 Time:20100805T084547Z
Summary:meeting Description:None DateStart:20100630T090000 DateEnd:20100630T100000 Time:20100805T084547Z

我需要创建一个函数,在给定的“日期”和“时间”检索“摘要”。
例如,函数将有两个参数,日期和时间,这两个参数不会采用日期-时间格式。它需要检查函数参数中指定的日期和时间是否介于文件中datestart和dateend中的日期和时间之间。
我不知道如何从上面指定的格式(即20100629T110000)中检索时间和日期。我试着用下面的
line_time = datetime.strptime(time, "%Y%D%MT%H%M%S"),其中时间是“20100629T110000”,但是我得到了很多错误,比如“datetime.datetime没有strptime属性”。
做这个功能的正确方法是什么,提前谢谢。
编辑
这是我的错误
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

    ****************************************************************
    Personal firewall software may warn about the connection IDLE
    makes to its subprocess using this computer's internal loopback
    interface.  This connection is not visible on any external
    interface and no data is sent to or received from the Internet.
    ****************************************************************

>>>
Traceback (most recent call last):
  File "C:\Python24\returnCalendarstatus", line 24, in -toplevel-
    status = calendarstatus()
  File "C:\Python24\returnCalendarstatus", line 16, in calendarstatus
    line_time = datetime.strptime(time, "%Y%m%dT%H%M%S")
AttributeError: type object 'datetime.datetime' has no attribute 'strptime'
>>>

这是我的密码
import os
import datetime
import time
from datetime import datetime

def calendarstatus():

    g = open('calendaroutput.txt','r')
    lines = g.readlines()
    for line in lines:
        line=line.strip()
        info=line.split(";")
        summary=info[1]
        description=info[2]
        time=info[5];
        line_time = datetime.strptime(time, "%Y%m%dT%H%M%S")
        return line_time.year

status = calendarstatus()

最佳答案

不要混淆the datetime modulethe datetime Objects in the module
模块没有strptime函数,但对象有一个strptime类方法:

>>> time = "20100629T110000"
>>> import datetime
>>> line_time = datetime.strptime(time, "%Y%m%dT%H%M%S")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'strptime'
>>> line_time = datetime.datetime.strptime(time, "%Y%m%dT%H%M%S")
>>> line_time
datetime.datetime(2010, 6, 29, 11, 0)

请注意,第二次我们必须将类引用为datetime.datetime
或者,您可以只导入类:
>>> from datetime import datetime
>>> line_time = datetime.strptime(time, "%Y%m%dT%H%M%S")
>>> line_time
datetime.datetime(2010, 6, 29, 11, 0)

另外,我把你的format string%Y%D%MT%H%M%S改成了%Y%m%dT%H%M%S我想这就是你想要的。

09-30 14:26
查看更多