Create timestamp.py

This commit is contained in:
tcely 2025-04-21 15:12:36 -04:00 committed by GitHub
parent f87ffdf104
commit 7ae75edffc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -0,0 +1,35 @@
import datetime
from django.utils import timezone
posix_epoch = datetime.datetime.utcfromtimestamp(0)
utc_tz = datetime.timezone.utc
def add_epoch(seconds):
assert seconds is not None
assert seconds >= 0, 'seconds must be a positive number'
return timedelta(seconds=seconds) + posix_epoch
def subtract_epoch(arg_dt, /):
epoch = posix_epoch.astimezone(utc_tz)
utc_dt = arg_dt.astimezone(utc_tz)
return utc_dt - epoch
def datetime_to_timestamp(arg_dt, /):
timestamp = subtract_epoch(arg_dt).total_seconds()
try:
timestamp_int = int(timestamp)
except (TypeError, ValueError,):
pass
else:
return timestamp_int
return timestamp
def timestamp_to_datetime(seconds, /):
return add_epoch(seconds=seconds).astimezone(utc_tz)