This repository has been archived by the owner on Dec 31, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
dtutils.py
executable file
·95 lines (66 loc) · 2.02 KB
/
dtutils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import logging
from datetime import datetime
from pytz import timezone
import pytz
MINS_IN_HOUR = 60
SECONDS_IN_MIN = 60
DAY_IN_MINS = 24 * MINS_IN_HOUR
TZ = timezone('Europe/Amsterdam')
UTC = pytz.utc
EPOCHE = datetime(1970, 1, 1, tzinfo=None)
def utc_datetime_now():
dt = local_datetime_now().astimezone(UTC)
logging.debug('utc_datetime_now(): %s', dt)
return dt
def utc_date_now():
return utc_datetime_now().date()
def utc_time_now():
return utc_datetime_now().time()
def utc_timestamp_now():
return to_timestamp(utc_datetime_now())
def local_datetime_now():
dt = TZ.localize(datetime.now())
logging.debug('local_datetime_now(): %s', dt)
return dt
def local_date_now():
return local_datetime_now().date()
def local_time_now():
return local_datetime_now().time()
def to_timestamp(dt):
logging.debug('to_timestamp(%s)', dt)
utc_dt = dt
if utc_dt.tzinfo:
utc_dt = utc_dt.replace(tzinfo=None) - utc_dt.utcoffset()
logging.debug('utc_dt: %s', utc_dt)
ts = (utc_dt - EPOCHE).total_seconds()
logging.debug('ts: %d', ts)
return ts
def to_day_timestamp(dt):
logging.debug('to_day_timestamp(%s)', dt)
ts = (datetime(dt.year, dt.month, dt.day, tzinfo=None)- EPOCHE).total_seconds()
logging.debug('ts: %d', ts)
utc_offset = dt.utcoffset()
if utc_offset:
logging.debug('dt.utcoffset(): %s', utc_offset)
ts -= utc_offset.total_seconds()
logging.debug('ts: %d', ts)
return ts
def is_today(dt):
return dt.date() == utc_date_now()
def adjust_time(dt, tod_in_mins, force=True):
d = dt
t = tod_in_mins
if force:
d = dt.replace(hour=t // MINS_IN_HOUR, minute=t % MINS_IN_HOUR, second=0)
else:
# assume day is 'now'
t = d.hour * MINS_IN_HOUR + d.minute
# don't allow tod to be set in the past
if tod_in_mins > t:
t = tod_in_mins
d = dt.replace(hour=t // MINS_IN_HOUR, minute=t % MINS_IN_HOUR, second=0)
return d, t
def convert_date_to_datetime(date, time=None):
if time == None:
return TZ.localize(datetime.combine(date, datetime.min.time()))
return TZ.localize(datetime.combine(date, time))