How To Remove Leading Zeroes With Python Dates

How do you remove leading zeroes in Python formatted dates?

I have been sending data through to a Suitescript API endpoint and have received the error that the date information I am sending through needs to be of the format D/M/YYYY , here’s the error specifically:

"type":"error.SuiteScriptError",
"name":"INVALID_FLD_VALUE",
"message":"Invalid date value (must be D/M/YYYY)"...

Currently, the way the date is formatted and sent from my Python code is as follows:

my_date = f"{date_object:%d/%m/%Y}

The f-string enables me to construct the date_object variable using Python’s 1989 C format codes .

However, a date such as the 1st March 2023 will produce the following output using the above code:

01/03/2023

So how do you remove the leading zeroes for the date and month values to comply with Netsuite’s date configuration?

Thankfully, there’s an excellent, succinct answer provided on Stack Overflow here where you can modify the format component of your f-string by adding one character (I’m using OSX):

my_date = f"{date_object:%-d/%-m/%Y}

Notice the dash between the % and the d character. It’s changed from %d to %-d for the date of the month component.

Therefore, applying the same date of 1st March 2023 (as used above) produces the following result:

1/3/2023

Therefore, if you are using Python to send data through to a Suitescript endpoint (such as a RESTlet) be sure to use the above to strip away any leading zeroes from your dates.

Still Doesn’t Work?

If you find it still doesn’t work in your Suitescript code then you may need to apply the format.parse() function to convert the string into a date data type.

Like so:

const ssDate = format.parse({type: format.Type.DATE, value: python_date});

This will enable Suitescript to convert the standard D/M/YYYY format date into an actual Javascript date that can be used elsewhere in your code (especially if you’re inserting the date into a date field, compared to it being used as a saved search filter).

Remove Leading Zero In Formatted Date In Python: Summary

To remove leading zeroes in a formatted date string insert the dash between the % and the date field characters (such as d for date, and m for month) if you’re on a Mac.

Therefor the final formatted string would look something like this: %-d/%-m/%Y

Photo of author
Ryan Sheehy
Ryan has been dabbling in code since the late '90s when he cut his teeth exploring VBA in Excel. Having his eyes opened with the potential of automating repetitive tasks, he expanded to Python and then moved over to scripting languages such as HTML, CSS, Javascript and PHP.