問題內容
正如您從以下內容中可能了解到的那樣,我不是一個非常熟練的程序員。盡管如此,我正在嘗試編寫一個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
登錄后復制