正如您从以下内容中可能了解到的那样,我不是一个非常熟练的程序员。尽管如此,我正在尝试编写一个python程序,用于从icalendar格式的文件导入数据并将其存储在数据库中。该文件多次出现如下所示的情况(跳过不相关的信息):
begin:vevent uid:tu1586072026 dtstamp:20240125t161430z summary:my meeting description:none ... created:20231004t161313z last-modified:20231023t162939z end: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))
以正确的方式打印前两个后出现错误:
dtstamp: 2024-01-25 16:14:30+00:00 created: 2023-10-04 16:13:13+00:00 traceback (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 calendar from datetime import datetime with 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!")
输出,例如最后修改时间丢失:
VEVENT CREATED: 2023-10-04 16:13:13+00:00 DTSTAMP: 2024-01-25 16:14:30+00:00 LAST-MODIFIED -> does not exist! UID: TU1586072026 SUMMARY: My meeting DESCRIPTION: None
以上是python中使用icalendar解析vDDDTypes数据的问题的详细内容。更多信息请关注PHP中文网其他相关文章!