已连接到Google Calendar API的Python项目。当我开始运行程序时,“今天”部分运行良好。但是,当我在Google日历上设置另一个时间表时,假设今天是2月13日。然后我将日期设置为2月16日,并尝试在python上调用它,但返回“未发现即将发生的事件”。我的年份或其他年份有问题吗?我在youtube上观看了本教程“ Python语音助手教程#4-从语音中获取日期”,我不知道问题出在哪里。我按部就班地观看了整个视频,但仍然出现错误。先感谢您。
def get_date(text):文字= text.lower()今天= datetime.date.today()
if text.count("today") > 0:
return today
day = -1
day_of_week = -1
month = -1
year = today.year
for word in text.split():
if word in MONTHS:
month = MONTHS.index(word) + 1
elif word in DAYS:
day_of_week = DAYS.index(word)
elif word.isdigit():
day = int(word)
else:
for ext in DAY_EXTENTIONS:
found = word.find(ext)
if found > 0:
try:
day = int(word[:found])
except:
pass
if month < today.month and month != -1:
year = year+1
# This is slighlty different from the video but the correct version
if month == -1 and day != -1: # if we didn't find a month, but we have a day
if day < today.day:
month = today.month + 1
else:
month = today.month
if month == -1 and day == -1 and day_of_week != -1:
current_day_of_week = today.weekday()
dif = day_of_week - current_day_of_week
if dif < 0:
dif += 7
if text.count("next") >= 1:
dif += 7
return today + datetime.timedelta(dif)
if month == -1 or day == -1:
return None
if day != -1: # FIXED FROM VIDEO
return datetime.date(month=month, day=day, year=year)
仅使用dateutil库将字符串解析为日期(您需要pip install python-dateutil
)
from dateutil.parser import parse
date_given = parse(text)
print(date_given)
它倾向于做正确的事...
如果需要更明确的控制,则应使用
date_given = datetime.datetime.strptime(formatString, dateString)
如果您需要查看两个日期之间的差异,请减去它们
datetime.datetime.now() - date_given