使用日期时间和使用python操作日期字符串
我有一个以下格式的文件
Summary:meeting Description:None DateStart:20100629T110000 DateEnd:20100629T120000 Time:20100805T084547Z Summary:meeting Description:None DateStart:20100630T090000 DateEnd:20100630T100000 Time:20100805T084547Z 我需要创建一个函数,在给定的“日期”和“时间”检索“摘要”. 我不知道如何从上面指定的格式[即20100629T110000]检索时间和日期.我试图使用以下内容 什么是正确的方式来做这个功能,提前谢谢. ………………..编辑……………. 这是我的错误 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:Python24returnCalendarstatus",line 24,in -toplevel- status = calendarstatus() File "C:Python24returnCalendarstatus",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 module与
the datetime Objects in the module混淆.
该模块没有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) 请注意我们第二次将该类引用为datetime.datetime. 或者,您只需导入该类: >>> from datetime import datetime >>> line_time = datetime.strptime(time,0) 此外,我将你的format string从%Y%D%MT%H%M%S改为%Y%m%dT%H%M%S我认为这是你想要的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |