2

I'm trying to use the Google Calendar API for python and want to change the format of the date it's outputting. I've tried using dateutil and strftime, but couldn't get it to work.....

Right now it's outputting yyyy-mm-dd hh:mm:ss-hh:mm "Event Name".

I want it to just display either yyyy-mm-dd, or in a format like "Apr 15, 2018".

Thank you and much appreciated!

"""
Shows basic usage of the Google Calendar API. Creates a Google Calendar API
service object and outputs a list of the next 10 events on the user's calendar.
"""
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import datetime
import time

# Setup the Calendar API
SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('calendar', 'v3', http=creds.authorize(Http()))

# Call the Calendar API
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
print('Getting the upcoming 10 events')
events_result = service.events().list(calendarId='primary', timeMin=now,
                                      maxResults=10, singleEvents=True,
                                      orderBy='startTime').execute()
events = events_result.get('items', [])

outFile = open('sample.txt' , 'w')

if not events:
    print('No upcoming events found.')


for event in events:
    start = event['start'].get('dateTime', event['start'].get('date'))

    print(start, event['summary'])

    outFile.write(str(event['summary']))
    outFile.write('  ')
    outFile.write(start)
    outFile.write('\n')
outFile.close()
Jae Park
  • 23
  • 4
  • possible duplicate of https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object – noogui Apr 18 '18 at 06:00

3 Answers3

1

You probably have found a solution to this question but another question brought me to this 'Unanswered' question.

Same answer..

You can do it using dateutil.parser and datetime.datetime.strftime together.

from dateutil.parser import parse as dtparse
from datetime import datetime as dt

start = '2018-12-26T10:00:00+01:00'   # Let's say your start value returns this as 'str'
tmfmt = '%d %B, %H:%M %p'             # Gives you date-time in the format '26 December, 10:00 AM' as you mentioned

# now use the dtparse to read your event start time and dt.strftime to format it
stime = dt.strftime(dtparse(start), format=tmfmt)

Output:

Out[23]: '26 December, 10:00 AM'

Then use the below command to print the event or combining the 4 outfile.write commands to one, write to the file as below:

print(stime, event['summary'])
outFile.write("{}\t{}\n".format(str(event['summary']), stime)
ParvBanks
  • 1,138
  • 6
  • 15
0

I'm assuming the start variable contains the datetime object you want to print. If so, you can format it by calling strftime (think: string from time). Returns a string from a datetime object:

date_format = '%Y-%m-%d'
print(start.strftime(date_format), event['summary'])

The documentation (link) contains a table that explains the various formatting options

JayFresco
  • 264
  • 2
  • 11
  • I get the error: AttributeError: 'unicode' object has no attribute 'strftime' Do I have to install strftime? – Jae Park Apr 18 '18 at 01:11
  • Maybe strftime isn't working because the output from my code is a time range instead of just a specific date and time – Jae Park Apr 18 '18 at 01:19
0

For those who are looking for the datetime format to convert Python's datetime to Google's API format, you can use the following:

datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
Sahar
  • 319
  • 3
  • 12