PHP前端开发

python中使用icalendar解析vDDDTypes数据的问题

百变鹏仔 1天前 #Python
文章标签 数据
问题内容

正如您从以下内容中可能了解到的那样,我不是一个非常熟练的程序员。尽管如此,我正在尝试编写一个python程序,用于从icalendar格式的文件导入数据并将其存储在数据库中。该文件多次出现如下所示的情况(跳过不相关的信息):

begin:veventuid:tu1586072026dtstamp:20240125t161430zsummary:my meetingdescription:none...created:20231004t161313zlast-modified:20231023t162939zend:vevent

我的问题在于 last-modified 值的解码。

如果我运行:

print("dtstamp: " + str(component.get('dtstamp').dt))    print("created: " + str(component.get('created').dt))    print("modified: " + str(component.get('last-modified').dt))

以正确的方式打印前两个后出现错误:

立即学习“Python免费学习笔记(深入)”;

dtstamp: 2024-01-25 16:14:30+00:00created: 2023-10-04 16:13:13+00:00traceback (most recent call last):  file "/usr/lib/python3.11/tkinter/__init__.py", line 1948, in __call__    return self.func(*args)           ^^^^^^^^^^^^^^^^  file "/home/sailslack/coding/python/pim/cal_import.py", line 97, in ical_import    print("modified: " + str(component.get('last-modified').dt))                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^attributeerror: 'nonetype' object has no attribute 'dt'

如果我在最后一行不使用 .dt 属性:

print("dtstamp: " + str(component.get('dtstamp').dt))    print("created: " + str(component.get('created').dt))    print("modified: " + str(component.get('last-modified')))

我没有收到任何错误,但是:

dtstamp: 2024-01-25 16:14:30+00:00    created: 2023-10-04 16:13:13+00:00    modified: vDDDTypes(2023-10-23 16:29:39+00:00, Parameters({}))

看起来就像我应该像其他属性一样使用 .dt 属性。

我做错了什么?


正确答案


更新:此示例适用于我的 python 环境,现在使用 try 块来处理丢失的组件:

from icalendar import calendarfrom datetime import datetimewith open('icalendar.ics', 'rb') as e:    ecal = calendar.from_ical(e.read())    for component in ecal.walk():        if component.name == 'vevent':            print(component.name)            com_attr = ['created','dtstamp','last-modified']            for timing in com_attr:                try:                    print(f"{timing}: {component.get(timing).dt}")                except attributeerror:                    print(f"{timing} -> does not exist!")            com_text = ['uid','summary','description']            for tex in com_text:                try:                    print(f"{tex}: {component.get(tex)}")                                    except attributeerror:                    print(f"{tex} -> does not exist!")

输出,例如最后修改时间丢失:

VEVENTCREATED: 2023-10-04 16:13:13+00:00DTSTAMP: 2024-01-25 16:14:30+00:00LAST-MODIFIED -> does not exist!UID: TU1586072026SUMMARY: My meetingDESCRIPTION: None