Exemple #1
0
def rel_date(days_from_now=7, localtime=15, minutes_from_now=False):
    if days_from_now == 0 and minutes_from_now:
        event_day = datetime.datetime.now(
            MST()) + datetime.timedelta(minutes=minutes_from_now)
        event_day = event_day.replace(
            tzinfo=timezone.FixedOffset(-420))  # matches MST
    else:
        today = datetime.date.today()
        event_day = datetime.datetime.combine(
            today + datetime.timedelta(days=days_from_now),
            datetime.time(localtime))
        event_day = event_day.replace(tzinfo=timezone.FixedOffset(-300))
    return event_day
Exemple #2
0
    def __call__(self, request):
        if request.user.is_authenticated:
            timezone.activate(
                timezone.FixedOffset(request.user.timezone_offset))

        response = self.get_response(request)

        return response
Exemple #3
0
def parse_datetime_str(date_str):
    naive_date_str = ' '.join(date_str.split(' ')[:4])
    offset_str = date_str.split(' ')[4][-5:]
    offset_name = str(date_str.split(' ')[4][:-5])
    naive_dt = datetime.strptime(naive_date_str, '%b %d %Y %H:%M:%S')
    offset = int(offset_str[-4:-2])*60 + int(offset_str[-2:])
    if offset_str[0] == "-":
        offset = -offset
    return naive_dt.replace(tzinfo=timezone.FixedOffset(offset, offset_name))
Exemple #4
0
def utc_and_timezone_to_datetime(utc_datetime, timezone_offset):
    """ Convert a UTC datetime and a timezone offset into a datetime object.

        'utc_datetime' should be a datetime.datetime object in UTC.  We return
        a datetime.datetime object with the time zone set to the given timezone
        offset, measured in minutes
    """
    utc_datetime = utc_datetime.astimezone(timezone.utc)  # Make sure its UTC.
    date_time = utc_datetime.astimezone(timezone.FixedOffset(timezone_offset))
    return date_time
 def modified_time(self, name):
     """
     Returns the last modified time (as datetime object) of the file
     specified by name.
     """
     time_tuple = parsedate_tz(self._get_key(name, validate=True).last_modified)
     timestamp = datetime.datetime(*time_tuple[:6])
     offset = time_tuple[9]
     if offset is not None:
         # Convert to local time.
         timestamp = timezone.make_aware(timestamp, timezone.FixedOffset(offset))
         timestamp = timezone.make_naive(timestamp, timezone.utc)
     return timestamp
Exemple #6
0
 def test_fixedoffset_deprecation(self):
     msg = 'FixedOffset is deprecated in favor of datetime.timezone'
     with self.assertWarnsMessage(RemovedInDjango31Warning, msg) as cm:
         timezone.FixedOffset()
     self.assertEqual(cm.filename, __file__)
Exemple #7
0
 def test_fixedoffset_pickle(self):
     self.assertEqual(
         pickle.loads(pickle.dumps(timezone.FixedOffset(
             0, 'tzname'))).tzname(''), 'tzname')
Exemple #8
0
class Datetime(object):
    LOCAL_TZ = timezone.FixedOffset(
        8 * 60
    )  # 分钟. workaround: https://docs.djangoproject.com/zh-hans/2.2/_modules/django/utils/timezone/
    UTC = pytz.utc

    @staticmethod
    def localtime() -> datetime:
        return timezone.localtime()

    @staticmethod
    def timestamp() -> int:
        return int(timezone.localtime().timestamp())

    @staticmethod
    def replace_timezone(dt: datetime, tzinfo=LOCAL_TZ) -> datetime:
        """
        替换时区, 年月日时分秒都保持不变.
        :param dt:
        :param tzinfo: 指定参数dt的时区
        :return:
        """
        return dt.replace(tzinfo=tzinfo)

    @staticmethod
    def convert_timezone(dt: datetime, tzinfo=LOCAL_TZ) -> datetime:
        """
        转换时区, 年月日时分秒相应转换.
        :param dt:
        :param tzinfo: 指定参数dt的时区
        :return:
        """
        return dt.astimezone(tz=tzinfo)

    @staticmethod
    def from_microsecond(microsecond, tzinfo=LOCAL_TZ) -> datetime:
        """
        微妙转 datetime
        :param microsecond:
        :param tzinfo: 指定参数dt的时区
        :return:
        """
        timestamp = microsecond / 1000000.0
        return datetime.fromtimestamp(timestamp, tzinfo)

    @staticmethod
    def to_microsecond(dt: datetime) -> int:
        """
        datetime 转微妙
        :param dt:
        :return:
        """
        return int(dt.timestamp() * 1000000)

    @staticmethod
    def to_millisecond(dt: datetime) -> int:
        """
        datetime 转毫秒
        :param dt:
        :return:
        """
        return int(dt.timestamp() * 1000)

    @staticmethod
    def to_second(dt: datetime) -> int:
        """
        datetime 转秒
        :param dt:
        :return:
        """
        return int(dt.timestamp())

    @staticmethod
    def to_int_day(dt: date) -> int:
        """
        date 转日期整型. 如: date(2020, 01, 01) -> 20200101
        :param dt:
        :return:
        """
        return int(dt.strftime('%Y%m%d'))

    @staticmethod
    def from_millisecond(millisecond, tzinfo=LOCAL_TZ) -> datetime:
        """
        毫秒转 datetime
        :param millisecond:
        :param tzinfo: 指定参数dt的时区
        :return:
        """
        timestamp = millisecond / 1000.0
        return datetime.fromtimestamp(timestamp, tzinfo)

    @staticmethod
    def from_timestamp(timestamp, tzinfo=LOCAL_TZ) -> datetime:
        return datetime.fromtimestamp(timestamp, tzinfo)

    @staticmethod
    def from_date(d: date, tzinfo=LOCAL_TZ) -> datetime:
        dt = datetime.combine(d, datetime.min.time())
        return Datetime.replace_timezone(dt, tzinfo=tzinfo)

    @staticmethod
    def get_day_begin(dt: datetime) -> datetime:
        return datetime.combine(dt, datetime.min.time())

    @staticmethod
    def get_day_end(dt: datetime) -> datetime:
        return datetime.combine(dt, datetime.max.time())

    @staticmethod
    def to_str(dt: datetime, fmt='%Y-%m-%d %H:%M:%S'):
        """
        datetime 转换为 string
        :param dt:
        :param fmt: 常用 %Y-%m-%d %H:%M:%S.%f
        :return:
        """
        return dt.strftime(fmt)

    @staticmethod
    def from_str(string: str, fmt='%Y%m%d', tzinfo=LOCAL_TZ):
        """
        string 转成 datetime
        :param string:
        :param fmt: 常用 %Y-%m-%d %H:%M:%S.%f
            %a 星期几的简写
            %A 星期几的全称
            %b 月分的简写
            %B 月份的全称
            %c 标准的日期的时间串
            %C 年份的后两位数字
            %d 十进制表示的每月的第几天
            %D 月/天/年
            %e 在两字符域中,十进制表示的每月的第几天
            %F 年-月-日
            %g 年份的后两位数字,使用基于周的年
            %G 年分,使用基于周的年
            %h 简写的月份名
            %H 24小时制的小时
            %I 12小时制的小时
            %j 十进制表示的每年的第几天
            %m 十进制表示的月份
            %M 十时制表示的分钟数
            %n 新行符
            %p 本地的AM或PM的等价显示
            %r 12小时的时间
            %R 显示小时和分钟:hh:mm
            %S 十进制的秒数
            %f Microsecond as a decimal number, zero-padded on the left. 6位数字
            %t 水平制表符
            %T 显示时分秒:hh:mm:ss
            %u 每周的第几天,星期一为第一天 (值从0到6,星期一为0)
            %U 第年的第几周,把星期日做为第一天(值从0到53)
            %V 每年的第几周,使用基于周的年
            %w 十进制表示的星期几(值从0到6,星期天为0)
            %W 每年的第几周,把星期一做为第一天(值从0到53)
            %x 标准的日期串
            %X 标准的时间串
            %y 不带世纪的十进制年份(值从0到99)
            %Y 带世纪部分的十进制年份 (2020)
            %z,%Z 时区名称,如果不能得到时区名称则返回空字符。
            %% 百分号
        :return:
        """
        dt = datetime.strptime(string, fmt)
        return Datetime.replace_timezone(dt, tzinfo=tzinfo)

    @staticmethod
    def from_iso8601(string: str, tzinfo=LOCAL_TZ):
        dt = parse_datetime(string)
        return Datetime.convert_timezone(dt, tzinfo=tzinfo)

    @staticmethod
    def iter(start_date, end_date, seconds=86400):
        """
        :param start_date: 类型 date 或者 datetime
        :param end_date: 类型 date 或者 datetime
        :param seconds:
        :return:
        """
        assert type(start_date) == type(end_date) and type(start_date) in [
            date, datetime
        ]
        while start_date <= end_date:
            yield start_date
            start_date += timedelta(seconds=seconds)
 def test_override_fixed_offset(self):
     with timezone.override(timezone.FixedOffset(0, 'tzname')):
         self.assertEqual(timezone.get_current_timezone_name(), 'tzname')
Exemple #10
0
 def test_fixedoffset_dst(self):
     ZERO = datetime.timedelta(minutes=0)
     delta = datetime.timedelta(hours=0)
     self.assertEqual(timezone.FixedOffset().dst(delta), ZERO)
Exemple #11
0
 def test_fixedoffset_utcoffset(self):
     delta = datetime.timedelta(minutes=1)
     self.assertEqual(timezone.FixedOffset(1).utcoffset(None), delta)
def event_create(days_from_now=7,
                 localtime=15,
                 id=343775,
                 max_attendees=100,
                 attendee_count=20,
                 is_inactive=False,
                 is_awaiting_confirmation=False,
                 place_index=None,
                 minutes_from_now=False,
                 attend_page=False):
    """ 
        localtime = hour of the day
        To get an event time with more precision to the current time, 
        set days_from_now=0 and minutes_from_now to an integer, and
        choose a place_index with an MST locale.
    """
    now_utc = datetime.datetime.now(timezone.utc)

    if days_from_now == 0 and minutes_from_now:
        event_day = datetime.datetime.now(
            MST()) + datetime.timedelta(minutes=minutes_from_now)
        event_day = event_day.replace(
            tzinfo=timezone.FixedOffset(-420))  # matches MST
    else:
        today = datetime.date.today()
        event_day = datetime.datetime.combine(
            today + datetime.timedelta(days=days_from_now),
            datetime.time(localtime))
        event_day = event_day.replace(tzinfo=timezone.FixedOffset(-300))
    event_day_utc = event_day.astimezone(timezone.utc)
    place_loc = {}
    if place_index:
        place_loc = places_list[place_index]
    else:
        place_loc = places_list[random.randint(0, len(places_list) - 1)]

    objobj = None
    if not attend_page:
        objobj = {
            "starts_at":
            event_day,
            "starts_at_utc":
            event_day_utc,
            "hosts":
            user({
                "first_name": "Host First",
                "last_name": "Host-Last",
                "phone": "123-456-7890",
            }),
        }
    evt_obj = {
        "id":
        id,
        "obj":
        objobj,
        "starts_at":
        event_day,
        "starts_at_utc":
        event_day_utc,
        "max_attendees":
        max_attendees,
        "attendee_count":
        attendee_count,

        # all overridden by place_loc
        "address1":
        "1 Main St.",
        "city":
        "Somewhere, OH 44444",
        # "longitude":
        # "latitude":
        "directions":
        "Directions.",
        "get_starts_at_display":
        dateformat.format(event_day,
                          'l, M j, g:i A'),  # "Monday, Jan 1, 1:00 AM",
        "is_in_past":
        bool(now_utc > event_day_utc),
        "is_full":
        bool(attendee_count >= max_attendees),
        "is_open_for_signup":
        bool(days_from_now > 0 and not attendee_count >= max_attendees),
        "is_inactive":
        is_inactive,
        "status": ("active" if not is_inactive else "cancelled"),
        "is_awaiting_confirmation":
        is_awaiting_confirmation,
        "note_to_attendees":
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
        "public_description":
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
        "title":
        "Event Title {}".format(place_index),
        "venue":
        "Venue Name",
    }
    evt_obj.update(place_loc)
    return evt_obj