我有一个以下格式的文件
Summary:meeting Description:None DateStart:20100629T110000 DateEnd:20100629T120000 Time:20100805T084547Z
Summary:meeting Description:None DateStart:20100630T090000 DateEnd:20100630T100000 Time:20100805T084547Z
Run Code Online (Sandbox Code Playgroud)
我需要创建一个函数,在给定的"日期"和"时间"检索"摘要".例如,函数将有两个参数,日期和时间,它们不是日期时间格式.它需要检查函数参数中指定的日期和时间是否在文件中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'
>>>
Run Code Online (Sandbox Code Playgroud)
这是我的代码
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()
Run Code Online (Sandbox Code Playgroud)
不要混淆的datetime
模块与该datetime
模块中的对象.
该模块没有任何strptime
功能,但Object确实有一个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)
Run Code Online (Sandbox Code Playgroud)
请注意我们第二次将该类引用为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)
Run Code Online (Sandbox Code Playgroud)
另外,我改变了你的格式字符串来自%Y%D%MT%H%M%S
于%Y%m%dT%H%M%S
我认为这是你想要的.
您需要实际阅读适合您的Python版本的文档.见注释上strptime
的文档的日期时间:
版本2.5中的新功能.
你正在使用2.4版本.您需要使用该文档中提到的解决方法:
import time
import datetime
[...]
time_string = info[5]
line_time = datetime(*(time.strptime(time_string, "%Y%m%dT%H%M%S")[0:6]))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6849 次 |
最近记录: |