How can three int variables, start_year, start_month, and start_day, which are 2024, 3, and 4 respectively, be concatenated into a date variable (date)?

date(start_year, start_month, start_day)

The script above aborted with an error:

Syntax Error: [line #1] The function [date] expects 0~1 argument(s), but the actual number of arguments is: 3. 

The following script also failed:

date(concat([start_year, start_month, start_day],'.'))

=> Failed to convert the string to DATE

Because the month and day must be two-digit values.

Later, I came up with a solution, but it's quite complicated:

def pad_with_zero(num){
  res = string(num)
  if(strlen(res) == 1) res = concat('0',res)
  return(res)
}

date(concat([start_year, pad_with_zero(start_month), pad_with_zero(start_day)],'.'))

Is there a simpler method that can achieve this with just one function?

3

There are 3 best solutions below

0
JaneYe On

You can pad 0 to meet the date format specifications of DolphinDB.

start_year="2024" 
start_month="3" 
start_day="4"
concat([start_year, lpad(start_month, 2, "0"), lpad(start_day, 2, "0")], ".").date()


x=start_year+lpad(start_month, 2, "0")+lpad(start_day, 2, "0")
temporalParse(x, "yyyyMMdd")
0
Uri Loya On

In python you can do:

date = '{}.{:02d}.{:02d}'.format(start_year, start_month, start_day)
parsed_date = datetime.strptime(date, '%Y.%m.%d').date()

You can find more details in this answer: what does {:02d} mean in Python

1
Shaiming Pai On
const start_year = 2024;
const start_month = 3; // Note: Months are zero-based (0 for January, 1 for February, etc.)
const start_day = 4;

// Create a new Date object using the provided year, month, and day
const date = new Date(start_year, start_month - 1, start_day); // Subtract 1 from month to make it zero-based

console.log(date); // Output: 2024-04-04T00:00:00.000Z