pythondatetimeicalendarrfc5545

python icalendar setting dtstart properly


I'm setting up a script to format a bunch of hockey schedules into .ics files, using python and the python package iCalendar.

When I set:

event.add('dtstart', game_datetime[i])
event.add('dtend', game_datetime[i]+timedelta(hours=i))

I get the following in the resultant .ics file:

DTSTART;VALUE=DATE-TIME:20141019T140500
DTEND;VALUE=DATE-TIME:20141019T160500

Clearly not ideal; it appears to be passing over the object and not the value. So when I try and set it using strftime() as following:

#event.add('dtstart', game_datetime[i].strftime('%Y%m%dT%H%M%SZ'))
#event.add('dtend', (game_datetime[i]+timedelta(hours=i)).strftime('%Y%m%dT%H%M%SZ'))

I get the following error:

File "D:\schedule_format.py", line 72, in <module>
event.add('dtstart', game_datetime[i].strftime('%Y%m%dT%H%M%SZ'))
File "C:\Python27\lib\site-packages\icalendar-3.9.dev0-py2.7.egg\icalendar\cal.py", line 171, in add
value = self._encode(name, value, parameters, encode)
File "C:\Python27\lib\site-packages\icalendar-3.9.dev0-py2.7.egg\icalendar\cal.py", line 123, in _encode
obj = klass(value)
File "C:\Python27\lib\site-packages\icalendar-3.9.dev0-py2.7.egg\icalendar\prop.py", line 276, in __init__
raise ValueError('You must use datetime, date, timedelta or time')
ValueError: You must use datetime, date, timedelta or time

So clearly I'm supposed to be using a datetime object, but apparently I'm not using it correctly?


Solution

  • i don't know what you have in game_datetime but i faced this problem like you and use like this for date type property and it's work:

    from time import strftime,gmtime
    from icalendar import Calendar,Parameters,Todo
    import icalendar
    from datetime import *
    
    year = int(strftime("%Y", gmtime()))
    month = int(strftime("%m", gmtime()))
    day = int(strftime("%d", gmtime()))
    hour = int(strftime("%H", gmtime()))
    minute = int(strftime("%M", gmtime()))
    second = int(strftime("%S", gmtime()))
    
    temp = Todo()
    temp.add('CREATED',datetime(year,month,day,hour,minute,second))
    

    you should change 'CREATED' to date type you want