Fakultas Ilmu Komputer UI

utils.py 1.47 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
from datetime import datetime, timedelta
from math import floor, ceil
from random import randint, choice, choices, sample, random
from string import ascii_letters

from django.utils import timezone, lorem_ipsum


SECONDS_IN_DAY = 86400


12
def get_random_color():
13
14
15
16
    color = "%06x" % randint(0, 0xFFFFFF)
    return color


17
def get_lorem_with_length(n):
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    while True:
        s = lorem_ipsum.sentence()
        if len(s) < n:
            return s


def get_time_before(datetime, delta):
    return datetime - timedelta(seconds=delta)


def get_time_after(datetime, delta):
    return datetime + timedelta(seconds=delta)


def get_delta_in_seconds(s, e):
    return int((e-s).total_seconds())


def get_random_datetime(start_date, end_date, max_delta_seconds=None, min_delta_seconds=None):
    delta = get_delta_in_seconds(start_date, end_date)
    lower = 0 if min_delta_seconds is None else min_delta_seconds
    upper = delta if max_delta_seconds is None else max_delta_seconds
    delta = randint(lower, upper)
    return start_date + timedelta(seconds=delta)


def generate_list_of_random_datetime(start, end, n):
    res = []
46
    for _ in range(n):
47
48
49
50
51
52
53
54
55
56
57
58
        res.append(get_random_datetime(start, end))
    res.sort()
    return res


def get_last_year():
    datetime = timezone.now() - timedelta(days=365)
    datetime = datetime.replace(hour=0, minute=0, second=0, microsecond=0)
    return datetime


def generate_random_string(n):
59
    return(''.join(choice(ascii_letters) for _ in range(n)))