使用Python处理日期时间和日期字符串

3 投票
2 回答
8315 浏览
提问于 2025-04-16 02:34

我有一个文件,里面的格式是这样的:

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"),其中time是“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()

2 个回答

6

你需要认真阅读与你的Python版本相对应的文档。看看关于strptime的说明,在datetime的文档中:

在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]))
6

不要把datetime模块模块里的datetime对象搞混了。

模块本身没有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)

还有,我把你的格式字符串%Y%D%MT%H%M%S改成了%Y%m%dT%H%M%S,我觉得这样更符合你的需求。

撰写回答