zulip/zerver/lib/timestamp.py

43 lines
1.3 KiB
Python
Raw Normal View History

from __future__ import absolute_import
import datetime
import calendar
from django.utils.timezone import utc as timezone_utc
2017-02-28 18:39:36 +01:00
def floor_to_hour(dt):
# type: (datetime.datetime) -> datetime.datetime
2017-02-28 18:39:36 +01:00
return datetime.datetime(*dt.timetuple()[:4]) \
.replace(tzinfo=dt.tzinfo)
2017-02-28 18:39:36 +01:00
def floor_to_day(dt):
# type: (datetime.datetime) -> datetime.datetime
2017-02-28 18:39:36 +01:00
return datetime.datetime(*dt.timetuple()[:3]) \
.replace(tzinfo=dt.tzinfo)
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
class TimezoneNotUTCException(Exception):
pass
2017-02-28 18:39:36 +01:00
def datetime_to_timestamp(dt):
# type: (datetime.datetime) -> int
if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) != timezone_utc.utcoffset(dt):
2017-02-28 18:39:36 +01:00
raise TimezoneNotUTCException("Datetime %s to be converted does not have a UTC timezone." % (dt,))
return calendar.timegm(dt.timetuple())