zulip/zerver/lib/timestamp.py

53 lines
1.6 KiB
Python
Raw Normal View History

import datetime
import calendar
from django.utils.timezone import utc as timezone_utc
class TimezoneNotUTCException(Exception):
pass
def verify_UTC(dt):
# type: (datetime.datetime) -> None
if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) != timezone_utc.utcoffset(dt):
raise TimezoneNotUTCException("Datetime %s does not have a UTC timezone." % (dt,))
def convert_to_UTC(dt):
# type: (datetime.datetime) -> datetime.datetime
if dt.tzinfo is None:
return dt.replace(tzinfo=timezone_utc)
return dt.astimezone(timezone_utc)
2017-02-28 18:39:36 +01:00
def floor_to_hour(dt):
# type: (datetime.datetime) -> datetime.datetime
verify_UTC(dt)
2017-02-28 18:39:36 +01:00
return datetime.datetime(*dt.timetuple()[:4]) \
.replace(tzinfo=timezone_utc)
2017-02-28 18:39:36 +01:00
def floor_to_day(dt):
# type: (datetime.datetime) -> datetime.datetime
verify_UTC(dt)
2017-02-28 18:39:36 +01:00
return datetime.datetime(*dt.timetuple()[:3]) \
.replace(tzinfo=timezone_utc)
2017-02-28 18:39:36 +01:00
def ceiling_to_hour(dt):
# type: (datetime.datetime) -> datetime.datetime
2017-02-28 18:39:36 +01:00
floor = floor_to_hour(dt)
if floor == dt:
return floor
return floor + datetime.timedelta(hours=1)
2017-02-28 18:39:36 +01:00
def ceiling_to_day(dt):
# type: (datetime.datetime) -> datetime.datetime
2017-02-28 18:39:36 +01:00
floor = floor_to_day(dt)
if floor == dt:
return floor
return floor + datetime.timedelta(days=1)
def timestamp_to_datetime(timestamp):
# type: (float) -> datetime.datetime
return datetime.datetime.fromtimestamp(float(timestamp), tz=timezone_utc)
2017-02-28 18:39:36 +01:00
def datetime_to_timestamp(dt):
# type: (datetime.datetime) -> int
verify_UTC(dt)
2017-02-28 18:39:36 +01:00
return calendar.timegm(dt.timetuple())