Search code examples
robotframeworkpython-datetime

How to always get a leading 0 in robot framework DateTime


I am currently trying to figure out how to always get a leading 0 when getting current date time.

The following is the way I am currently doing it:

${date} =   Get Current Date  result_format=datetime
${dateyear}=  Convert To String    ${date.year}
${datemonth}=  Convert To String    ${date.month}
${dateday}=  Convert To String    ${date.day}
${datehour}=  Convert to string  ${date.hour}
${dateminute}=  Convert to string  ${date.minute}

The problem is that when I get date.day/minute/hour/, I get back 1-9 instead of 01-09. I am using the values to enrich a json, which expects 2 characters for each, so passing 1 results in an error, while passing 01 will work fine.


Solution

  • You can use zfill() function to pad strings:

    ${dateminute}=  Set Variable    5
    ${dateminute}=  Evaluate        '${dateminute}'.zfill(2)