django_coreprotect/utils.py

38 lines
967 B
Python
Raw Normal View History

import ast
from datetime import datetime, timedelta
from typing import Any, Optional
def checkbox(value: str) -> bool:
return True if value == "on" else False
def safe_int(value: Any) -> int:
try:
return int(value)
except:
return 0
def time_to_form(date_time: str) -> Optional[datetime]:
if date_time == "~T":
return datetime.today()
elif date_time == "~N":
return datetime.now()
elif date_time == "~Y":
return datetime.today() - timedelta(days=1)
elif date_time == "":
return None
else:
return datetime.utcfromtimestamp(float(date_time))
def form_to_time(date_time):
dt = ast.literal_eval(date_time)
if dt[0] in ["~T", "~N", "~Y"]:
return dt[0]
else:
dt[0] = dt[0] if dt[0] else datetime.now().strftime("%Y-%m-%d")
dt[1] = dt[1] if dt[1] else "00:00:00"
return datetime.strptime(" ".join(dt), "%Y-%m-%d %H:%M:%S").timestamp()