Reputation: 119
Based on the example I found here I want to grab icalendar data and process it. This my code so far:
from datetime import datetime, timedelta
from icalendar import Calendar
import urllib
import time
ics = urllib.urlopen('https://www.google.com/calendar/ical/xy/basic.ics').read()
ical1 = Calendar.from_ical(ics)
for vevent in ical1.subcomponents:
if vevent.name == "VEVENT":
title = str(vevent.get('SUMMARY').encode('utf-8'))
start = vevent.get('DTSTART').dt # datetime
end = vevent.get('DTEND').dt # datetime
print title
print start
print end
print type(start)
print "---"
It is fetching the title and start+end date from my google calender. This working and the output looks like this:
This is a Test Title
2012-12-20 15:00:00+00:00
2012-12-20 18:00:00+00:00
<type 'datetime.datetime'>
---
Another Title
2012-12-10
2012-12-11
<type 'datetime.date'>
---
...
As you can see the start and end date can be of type datetime.datetime
or datetime.date
. It depends on whether I have an entry in google calender for 2 whole days (then it is a datetime.date
) or for a time period e.g. 3 hours (then it is a datetime.datetime
. I need to only print dates/datetimes from today and for the next 4 weeks. I had problems comparing dates and datetimes (its seems like it is not possible) so I failed to do that. How can I compare datetimes and dates conserving the data types? If I need to "cast" them, its ok. I was not able to print "today + 4 weeks", only "4 weeks".
Upvotes: 3
Views: 351
Reputation: 11738
You will need to convert to a common type for comparison. Since both datetime's and date's have dates in common, it makes sense to convert -> date types. Just extract the date() from the datetime. For example:
>>> import datetime
>>> datetime.date(2014, 2, 22) == datetime.datetime.now().date()
True
Upvotes: 1
Reputation: 3341
Datetime objects can return an appropriate date object by calling date on them: start.date()
which then can be compared to another date object: start.date() < datetime.date.today() + datetime.timedelta(4*7)
Upvotes: 1