正如您從以下內容中可能了解到的那樣,我不是一個非常熟練的程式設計師。儘管如此,我正在嘗試編寫一個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中文網其他相關文章!