Having an issue with the PARSE_DATETIME function in BigQuery used with the day of year (%j) formatting element. The function seems to ignore the day of year element.
Eg.
Not a bug, neither an error! PARSE_DATETIME uses a format_string and a STRING representation of a DATETIME to return a DATETIME -> "2013243" does not represent a DATETIME string, not a DATE...
To achieve what you are looking for first get the day number - 1 and add it to date (first day of the year) and format the output to DATETIME
SELECT DATETIME(DATE_ADD((SELECT PARSE_DATE("%Y%j", "2013243")), INTERVAL CAST((SELECT SUBSTR("2013243", -3)) AS INT64) -1 DAY));
Output: 2013-08-31T00:00:00
I think that this is a bug that could be fixed! there is no logic in it working one way but not opposite!
Meantime, you can use below to achieve goal
#standardSQL
CREATE TEMP FUNCTION PARSE_DATETIME_WITH_DAYS(x STRING) AS (
DATETIME_ADD(PARSE_DATETIME('%Y%j', x), INTERVAL CAST(SUBSTR(x, -3) AS INT64) - 1 DAY)
);
SELECT PARSE_DATETIME_WITH_DAYS('2013243')
with result -
Row f0_
1 2013-08-31T00:00:00