Cannot pass date to Python script

2 posts / 0 new
Last post
cmkenny
Offline
Joined: 10/09/2018 - 04:27
Cannot pass date to Python script

I am trying to add a custom function to add working days (i.e exclusive of weekends and public holidays) to a date.
I've written the following Python which does this and works without issue in VS Code if you pass it a YYYYMMDD string

def add_weekday(date1,x):
    from numpy import busday_offset
    from datetime import datetime
    uk_bank_hols=['2022-05-02','2022-06-02']
    date1=str(date1)
    date1=datetime.strptime(date1,'%Y%m%d').date()
    #offset working days
    np_day_offsets = str(busday_offset(date1,x, holidays=uk_bank_hols))
    return np_day_offsets

 
If I try to pass a date or string column to it in IDEA I always get the same error:
Python generated the following error:
time data '' does not match format '%Y%m%d'
I've also tried:

  • stripping all non numeric characters from the string (e.g removing / - etc)
  • Unformatted dates (DD-MM-YYYY HH:MM:SS) and stripping/formatting the date in Python

I always get the same issue around time data not matching format, irrespective of the format passed and matched to an updated mask for strptime

Brian Element's picture
Brian Element
Offline
Joined: 07/11/2012 - 19:57

Hi cmkenny, here is the python code from one of the cwi custom date functions:


def cwi_DateDif(Date1,Date2,Difference):
    from datetime import datetime

    xtemp = "10000101"
    ytemp = "10000101"
    if(Date1>xtemp):
        xtemp = Date1
    if(Date2>ytemp):
        ytemp = Date2

    start_datetime = datetime.strptime(xtemp, '%Y%m%d')
    end_datetime = datetime.strptime(ytemp, '%Y%m%d')

We first check to make sure the data time is greater than Jan 1, 1000 as I believe that is the start date for Python datetime.  If it is less than we default to that.

We then use the datetime.striptime function to format it and place it in a variable and we are good to use it after that.

Hopefully that helps you out.  If you download the Custom Functions package from the IDEA lab there are lots of different python custom function there that you can check out and see how we do it.