Time and date formatting for scrape sensor

Hi all!
I want to take dates and hours of games from website of local stadium.
The data provided in a plaintext, so i created a scrape sensor, and it works, BUT!
This is how date looks on the website:
07/09/23 20:00
so I used this value template to convert it to time and date:
{{ value | replace('/', '.') }}
and it provides same date and time as it shown on website.
But how I can convert it in date and time parameters to use later in automations?

1 Like
{{ strptime(value|replace('/', '.'), '%d/%m/%y %H:%M') }}

Assuming Day/Month/Year, could be %m/%d/%y which would be Month/Day/Year as well :wink:

In any case see the time section of the templating docs.

@tom_l I think you’ve got a bug in your code though. the replace isn’t needed in the strptime and if it’s there it’s going to break the format evaluator given that you used ‘/’ in the evaluator instead of ‘.’

believe me I’m on it and many other resources, and it does not helps

ValueError: Template error: strptime got invalid input 'None' when rendering template '{{ strptime(value|replace('/', '.'), '%d/%m/%y %H:%M') }}' but no default was specified

Ah, yeah, you must supply a default to that function. Add , now() after the format string. This will cause it to render the current date time if the function fails for some reason. Which would basically happen if the string format changes on you or you end up with a null / empty string for your value.

same error

ValueError: Template error: strptime got invalid input 'None' when rendering template '{{ strptime(value, '%d/%m/%y %H:%M') | timestamp_custom('%Y-%m-%d %H:%M:%S', true, 'now()') }}' but no default was specified
{{ strptime(value, '%d/%m/%y %H:%M, now()) }}

That’s what I’m talking about. You have to supply the now() to the strptime function.

thank you! now it semi works
the output is correct, but when I’m configuring device_class: Timestamp for this scrape sensor, i’m getting warning in logs:

sensor.game1 rendered timestamp without timezone: 2023-09-07 20:00:00

You may want to consider changing that then to something like this:

{{ strptime(value + " TZ", '%d/%m/%y %H:%M %Z', now()) }}

Replace the TZ with your timezone “code”. For instance, I’m on the US West Coast so I would use PDT (since I’m currently in Pacific Daylight Time). That should force the timezone information.

Alternatively you could try this:

{{ strptime(value, '%d/%m/%y %H:%M', now()) | as_local()  }}

That might force your local timezone onto the resultant datetime object…

1 Like

Wow, great! The second option is exactly what i was looking for! Thank you so much! :beers: