1
0
mirror of https://github.com/home-assistant/core.git synced 2025-12-27 14:31:13 +00:00

Allow conversion from date strings to "unix" timestamp. (#1985)

"unix" timestamp is number of seconds since Jan 1, 1970 UTC.
This allows scripts that use templates to generate time
deltas in seconds if desired from state attributes such
as last_updated.

Some examples:

timestamp now is
{{ as_timestamp(now) }}

timstamp of last change is
{{ as_timestamp(states.binary_sensor.garage_door.last_changed) }}

seconds since last change is
{{ as_timestamp(now) - as_timestamp(states.binary_sensor.garage_door.last_changed) }}
This commit is contained in:
Charles Spirakis
2016-05-06 18:33:46 -07:00
committed by Paulus Schoutsen
parent ca0ea6c2f3
commit b86a1ece01
3 changed files with 26 additions and 0 deletions

View File

@@ -1,4 +1,5 @@
"""Provides helper methods to handle the time in HA."""
import calendar
import datetime as dt
import re
@@ -59,6 +60,17 @@ def as_utc(dattim):
return dattim.astimezone(UTC)
def as_timestamp(dt_value):
"""Convert a date/time into a unix time (seconds since 1970)."""
if hasattr(dt_value, "utctimetuple"):
parsed_dt = dt_value
else:
parsed_dt = parse_datetime(str(dt_value))
if not parsed_dt:
raise ValueError("not a valid date/time.")
return calendar.timegm(parsed_dt.utctimetuple())
def as_local(dattim):
"""Convert a UTC datetime object to local time zone."""
if dattim.tzinfo == DEFAULT_TIME_ZONE: