Python Forum
Print first day of the week as string in date format
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Print first day of the week as string in date format
#1
Hey guys, I'm new to Python and I'm struggling with getting the beginning of the week as a string.

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd
import win32com.client as win32
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from datetime import datetime, date, timedelta
import tkinter as tk
from tkinter import simpledialog
from tkcalendar import Calendar,DateEntry



SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'trans-falcon-327308-c2fe811f9ec7.json'
VIEW_ID = '178053840'

credentials = ServiceAccountCredentials.from_json_keyfile_name(KEY_FILE_LOCATION, SCOPES)

analytics = build('analyticsreporting', 'v4', credentials=credentials)

'''INPUT POPUP'''
ROOT = tk.Tk()

ROOT.withdraw()
# the input dialog
USER_INP = simpledialog.askstring(title="Manual Input",
                                  prompt="Number of Web Enquries for the week?:")



def initialize_analyticsreporting():
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  # Build the service object.
  analytics = build('analyticsreporting', 'v4', credentials=credentials)

  return analytics



def get_report(analytics):
  dateX = date.today()
  return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': str(dateX) , 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:users',},{'expression': 'ga:sessions',}],     
        }]
      }
  ).execute()


def print_response(response):
  ret_string="Report created on " + str(datetime.now()) + "\r\n" + "\r\n"
  for report in response.get('reports', []):
    columnHeader = report.get('columnHeader', {})
    metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])


    for row in report.get('data', {}).get('rows', []):
      dateRangeValues = row.get('metrics', [])

      for i, values in enumerate(dateRangeValues):

        '''RETURNS YES IAN TO EMAIL'''
        ret_string = ret_string + 'YES IAN!!' + "\r\n" + "\r\n"

        '''RETURNS DATE RANGE TO EMAIL'''
        #ret_string = ret_string + 'Date range:' + str(i) + "\r\n"

        '''DEFINES METRICS'''
        object_1 = values.get('values')

        '''RETURNS HUDDLE STATS'''
        ret_string = ret_string + 'Web Enquries:-' + 'So far this week - ' + str(USER_INP) + "\r\n"
        ret_string = ret_string + str(object_1[0]) + ' Visities to the site yesterday, ' + str(object_1[1]) + ' for the week' "\r\n"
        #ret_string = ret_string + 'Sessions on the site yesterday' + ':' + str(object_1[1]) + "\r\n"

        '''PRINTS HUDDLE STATS TO CMD'''
        print('Date range' + ':' + str(i))
        print('Users on the site yesterday' + ':' + str(object_1[0]) )
        print('Sessions on the site yesterday' + ':' + str(object_1[1]))
        #for metricHeader, value in zip(metricHeaders, values.get('values')):
        #print(object_1.get('name') + ':', value
        #  ret_string = ret_string + metricHeader.get('name') + ':' + str(value) + "\r\n"
        #  ret_string = ret_string + 'Users on the site yesterday' + ':' + str(value) + "\r\n"

  return ret_string

def send_outlook_email(subject, body , recipient):
    outlook_obj = win32.Dispatch("Outlook.Application")
    Msg = outlook_obj.CreateItem(0)
    Msg.To = recipient
    Msg.Subject = subject
    Msg.Body = body
    Msg.Send()

def main():
  analytics = initialize_analyticsreporting()
  response = get_report(analytics)
  str_body = print_response(response)
  str_subject = "GA Python script execution at " + str(datetime.now())
  str_recipient = 'EMAIL;'
  send_outlook_email(str_subject , str_body , str_recipient )

if __name__ == '__main__':
  main()
I have made dateX today's date, but what I want to show is the date of the last Saturday within the week. (25th Sep) for example.

Format needs to be YYY-MM-DD

TIA
Yoriz write Sep-28-2021, 11:54 AM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
>>> dateX = date.today()
>>> dateX
datetime.date(2021, 9, 28)
>>> sat = dateX + timedelta(days=5-dateX.weekday())
>>> sat
datetime.date(2021, 10, 2)
>>> sat.strftime("%Y-%m-%d")
'2021-10-02'
MyerzzD likes this post
Reply
#3
(Sep-28-2021, 03:40 PM)bowlofred Wrote:
>>> dateX = date.today()
>>> dateX
datetime.date(2021, 9, 28)
>>> sat = dateX + timedelta(days=5-dateX.weekday())
>>> sat
datetime.date(2021, 10, 2)
>>> sat.strftime("%Y-%m-%d")
'2021-10-02'

Worked a treat, thank you!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Modifying a date format jehoshua 17 535 Oct-29-2022, 08:44 PM
Last Post: jehoshua
  Format String NewPi 2 230 Oct-10-2022, 05:50 PM
Last Post: NewPi
  Remove a space between a string and variable in print sie 5 612 Jul-27-2022, 02:36 PM
Last Post: deanhystad
  Date format error getting weekday value Aggie64 2 608 May-29-2022, 07:04 PM
Last Post: Aggie64
  Can you print a string variable to printer hammer 2 760 Apr-30-2022, 11:48 PM
Last Post: hammer
  Convert Date to another format lonesoac0 2 855 Mar-17-2022, 11:26 AM
Last Post: DeaD_EyE
  Format SAS DATE Racer_x 0 510 Feb-09-2022, 04:44 PM
Last Post: Racer_x
  TypeError: not enough arguments for format string MaartenRo 6 1,141 Jan-09-2022, 06:46 PM
Last Post: ibreeden
  How can I compare 2 format of date? korenron 4 846 Dec-21-2021, 12:40 PM
Last Post: korenron
  string format challenge jfc 2 1,063 Oct-23-2021, 10:30 AM
Last Post: ibreeden

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020