我正试图在下个月内从ics文件中提取事件,但是创建自己的日期时间并与ics文件中的日期时间进行比较似乎不起作用,并给出了错误的TypeError: can't compare offset-naive and offset-aware datetimes。
我试着找到了这里的答案,但仍然得到了同样的错误。下面是我正在使用的代码。
def read_from_cal():
g = open('calendar.ics', 'rb')
gcal = Calendar.from_ical(g.read())
year = datetime.now().year
month = datetime.now().month
day = datetime.now().day
hour = datetime.now().strftime("%H")
minute = datetime.now().strftime("%M")
next_month = datetime(int(year), int(month)+1, int(day), int(hour), int(minute), 0, tzinfo=pytz.UTC)
#next_month = next_month.replace(tzinfo=pytz.UTC)
for component in gcal.walk():
if component.name == "VEVENT":
# time printed out in format:
# year-month-day hour:min:sec
summ = component.get('summary')
start = component.get('dtstart').dt
end = component.get('dtend').dt
if now <= start <= next_month:
print("Worked")
print(summ, start, end)我尝试过使用replace将我的时间更改为utc,只需将其放入next_month变量本身,它们都会给出相同的错误。
发布于 2021-09-04 01:08:25
我尝试使用这里生成的.ics文件,所以不可能是同一个问题,但在某些情况下,start是datetime.datetime,而在其他情况下是datetime.date。
此解决方案适用于我的.ics文件。
from icalendar import Calendar
from datetime import datetime
from dateutil.relativedelta import relativedelta
def read_from_cal():
g = open('example.ics', 'rb')
gcal = Calendar.from_ical(g.read())
today = datetime.now()
next_month = today + relativedelta(months=1)
for component in gcal.walk():
if component.name == "VEVENT":
summ = component.get('summary')
start = component.get('dtstart').dt
end = component.get('dtend').dt
if isinstance(start, datetime):
start = start.replace(tzinfo=None)
if start <= next_month:
print("Worked (datetime)")
print(summ, start, end)
else:
# some events are stored as a date
if start <= next_month.date():
print("Worked (date)")
print(summ, start, end)
read_from_cal()https://stackoverflow.com/questions/69050495
复制相似问题