2013-04-23 18:51:17 +02:00
|
|
|
from __future__ import absolute_import
|
|
|
|
|
2012-12-05 19:53:23 +01:00
|
|
|
import datetime
|
2012-12-11 23:08:17 +01:00
|
|
|
import calendar
|
2012-12-05 19:53:23 +01:00
|
|
|
from django.utils.timezone import utc
|
|
|
|
|
2016-07-29 21:52:45 +02:00
|
|
|
def is_timezone_aware(datetime_object):
|
|
|
|
# type: (datetime.datetime) -> bool
|
|
|
|
return datetime_object.tzinfo is not None
|
|
|
|
|
analytics: Simplify frequency and measurement interval options.
Change the CountStat object to take an is_gauge variable instead of a
smallest_interval variable. Previously, (smallest_interval, frequency)
could be any of (hour, hour), (hour, day), (hour, gauge), (day, hour),
(day, day), or (day, gauge).
The current change is equivalent to excluding (hour, day) and (day, hour)
from the list above.
This change, along with other recent changes, allows us to simplify how we
handle time intervals. This commit also removes the TimeInterval object.
2016-10-14 00:15:46 +02:00
|
|
|
def datetime_to_UTC(datetime_object):
|
|
|
|
# type: (datetime.datetime) -> datetime.datetime
|
|
|
|
if is_timezone_aware(datetime_object):
|
|
|
|
return datetime_object.astimezone(utc)
|
|
|
|
return datetime_object.replace(tzinfo=utc)
|
|
|
|
|
|
|
|
def floor_to_day(datetime_object):
|
|
|
|
# type: (datetime.datetime) -> datetime.datetime
|
|
|
|
return datetime.datetime(*datetime_object.timetuple()[:3]) \
|
|
|
|
.replace(tzinfo=datetime_object.tzinfo)
|
|
|
|
|
2012-12-05 19:53:23 +01:00
|
|
|
def timestamp_to_datetime(timestamp):
|
2016-06-03 23:32:55 +02:00
|
|
|
# type: (float) -> datetime.datetime
|
2012-12-05 19:53:23 +01:00
|
|
|
return datetime.datetime.utcfromtimestamp(float(timestamp)).replace(tzinfo=utc)
|
2012-12-11 23:08:17 +01:00
|
|
|
|
|
|
|
def datetime_to_timestamp(datetime_object):
|
2016-06-03 23:32:55 +02:00
|
|
|
# type: (datetime.datetime) -> int
|
2012-12-11 23:08:17 +01:00
|
|
|
return calendar.timegm(datetime_object.timetuple())
|
2016-07-29 21:52:45 +02:00
|
|
|
|
|
|
|
def datetime_to_string(datetime_object):
|
|
|
|
# type: (datetime.datetime) -> str
|
|
|
|
assert is_timezone_aware(datetime_object)
|
|
|
|
date_string = datetime_object.strftime('%Y-%m-%d %H:%M:%S%z')
|
|
|
|
return date_string
|