I have this following code to fetch data from google tasks and print it the way org-mode displays agenda: ```import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from console import fg, bg
import datetime as dt
If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/tasks.readonly"]
--- token will happen on the PC if it doesnt yet exist
TOKEN = "~/.google_tasks_api.token"
TOKEN = os.path.expanduser(TOKEN)
--- this is credential given by google
CRED = "~/.credentials_google0.json"
CRED = os.path.expanduser(CRED)
def dt_to_org(datim):
"""
from T Z to <2025-06-30 Mon 00:00>
"""
due_str = datim # item['due'] # e.g. '2025-07-01T00:00:00.000Z'
due_date = dt.datetime.strptime(due_str, "%Y-%m-%dT%H:%M:%S.%fZ").date() # compare to today etc..
p_date = due_date.strftime("%Y-%m-%d")
p_time = due_date.strftime("%H:%M:%S")
p_wday = due_date.strftime("%F")
#
result = due_date.strftime("%Y-%m-%d %a %H:%M")
return result
#
due_str = due_str.split("T")[0]
# plain date
today = dt.datetime.now(dt.timezone.utc).date()
tomorrow = today + dt.timedelta(days=1)
def main():
"""Shows basic usage of the Tasks API.
Prints the title and ID of the first 10 task lists.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists(TOKEN):
print(f"D... TOKEN: {TOKEN}")
creds = Credentials.from_authorized_user_file(TOKEN, SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
CRED, SCOPES
)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open(TOKEN, "w") as token:
token.write(creds.to_json())
TASKLIST = {}
try:
service = build("tasks", "v1", credentials=creds)
# Call the Tasks API
results = service.tasklists().list(maxResults=10).execute()
items = results.get("items", [])
if not items:
print("No task lists found.")
return
print("===============================Task lists:")
for item in items:
print(f"* {item['title']} ({item['id']})")
#TASKLIST.append(item['title'])
TASKLIST[item['id']] = item['title']
except HttpError as err:
print(err)
print("============================== Parsing tasklists ===")
for k, v in TASKLIST.items():
#print(k, v, TASKLIST.items())
#print(fg.green, v, fg.default, "Going for ID==", k, fg.green, v, fg.default, end="")
print(f"{fg.green}*", v, fg.default, end="\n")
try:
#service = build("tasks", "v1", credentials=creds)
# Call the Tasks API
results = service.tasks().list(tasklist=k).execute()
items = results.get("items", [])
print(f" /{len(items)} items:/" )
#print()
for item in items:
if 'status' in item:
if item['status'] == "completed":
#print(f"{fg.slategray} - {item['title']} : STAT: {item['status']} {fg.default}")
continue
#print(f" - {fg.cyan}{item['title']}{fg.default} ({item['id']})")
print(f"** TODO {fg.cyan}{item['title']}{fg.default} ")
if 'due' in item:
s_scheduled = dt_to_org(item['due'])
print(f"SCHEDULED: <{s_scheduled}>")
s_updated = dt_to_org(item['updated'])
print(f"UPDATED: [{s_updated}]") # inactive timestamp
if 'status' in item:
if item['status'] != "needsAction":
print(f" - STAT: {item['status']} ")
if 'due' in item:
s_scheduled = dt_to_org(item['due'])
due_str = item['due'] # e.g. '2025-07-01T00:00:00.000Z'
due_date = dt.datetime.strptime(due_str, "%Y-%m-%dT%H:%M:%S.%fZ").date()
#due_str = due_str.split("T")[0]
today = dt.datetime.now(dt.timezone.utc).date()
tomorrow = today + dt.timedelta(days=1)
if due_date == today:
print(f" - {fg.red} Due today {fg.default} ") # The allow day only via API
elif due_date == tomorrow:
print(f" - {fg.orange} Due tomorrow {fg.default} ") # They let day only
elif due_date < today:
print(f" - {fg.orange} Due in the PAST {fg.default} {due_str}") # They let day only
else:
#print("Due on", due_date)
print(f" - DUE : {due_str} ")
if 'notes' in item:
print(f" - NOTES: {item['notes']} ")
#results = service.tasks().get(tasklist=k, task=item['id'])
#TASKLIST.append(item['id'])
except HttpError as err:
print(err)
if name == "main":
main()