本文介绍了用icalendar解析日期并与python datetime比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.ics文件,我想从中提取当天发生的所有事件。我认为将icalendar DTSTART和DTEND转换为python日期时间时遇到麻烦。我试图按照上的文档进行操作。我得到的列表为空,情况并非如此。

I have an .ics file from which I would like to extract all of the events that occur on today's day. I think I'm having trouble converting the icalendar DTSTART and DTEND to python datetimes. I've tried to follow the documentation at icalendar.readthedocs.org. The list I'm getting is empty, which should not be the case.

这是我的代码:

import urllib2
import json
from datetime import datetime
from icalendar import Calendar, Event, vDatetime


def getTodayEvents(icsFile):
    cal = Calendar.from_ical(icsFile)
    today = datetime.now().date()
    entries = []
    for event in cal.walk('VEVENT'):
        dtstart = event['DTSTART']
        dtend = event['DTEND']
        start = vDatetime.from_ical(dtstart)      //Trouble here?
        end = vDatetime.from_ical(dtend)
        if start <= today <= end:
            entry = {'summary' : event['SUMMARY'] }
            entries.append(entry)
   output = json.dumps(entries)
   return output                                  //This list is empty

这是and ics条目:

And this is what the and ics entry looks like:

BEGIN:VEVENT
SUMMARY:Jonny Smith
DTSTART;VALUE=DATE:20140731
DTEND;VALUE=DATE:20150802
UID: 12345
CLASS:PUBLIC
PRIORITY:5
DTSTAMP:20141006T160145Z
TRANSP:OPAQUE
STATUS:CONFIRMED
SEQUENCE:0
LOCATION:Mansfield\, GA
X-MICROSOFT-CDO-APPT-SEQUENCE:0
X-MICROSOFT-CDO-BUSYSTATUS:FREE
X-MICROSOFT-CDO-INTENDEDSTATUS:BUSY
X-MICROSOFT-CDO-ALLDAYEVENT:TRUE
X-MICROSOFT-CDO-IMPORTANCE:1
X-MICROSOFT-CDO-INSTTYPE:0
X-MICROSOFT-DISALLOW-COUNTER:FALSE
END:VEVENT


推荐答案

DTSTART,DTEND属性具有 .dt 属性:

DTSTART, DTEND properties have .dt attribute:

#!/usr/bin/env python
import json
from datetime import date
import icalendar # $ pip install icalendar

today = date.today()
calendar = icalendar.Calendar.from_ical(ics_file)
entries = [dict(summary=event['SUMMARY'])
           for event in calendar.walk('VEVENT')
           if event['DTSTART'].dt <= today <= event['DTEND'].dt]
print(json.dumps(entries, indent=2, sort_keys=True))



输出



Output

[
  {
    "summary": "Jonny Smith"
  }
]

这篇关于用icalendar解析日期并与python datetime比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 22:46