blob: 4260ac7faa4e388c230e74142af2011c10e54e3c (
plain)
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
|
"""Time helpers.
* Camera local
* System local
* UTC
Timestamp to datetime
* Timestamp
* in UTC
* Timezone
* Implicit system local timezone
* No known timezone
* Known timezone
Datetime to timestamp
* always store as local time
* optionally with UTC offset
Part of the tagit module.
A copy of the license is provided with the project.
Author: Matthias Baumgartner, 2022
"""
# standard imports
from datetime import timezone, datetime, tzinfo, timedelta
# exports
__all__ = ('timestamp', 'from_timestamp')
## code ##
timestamp_loc = lambda dt: dt.replace(tzinfo=timezone.utc).timestamp()
timestamp_utc = lambda dt: dt.timestamp()
from_timestamp_loc = lambda ts: datetime.utcfromtimestamp(ts)
from_timestamp_utc = lambda ts: datetime.fromtimestamp(ts)
now = datetime.now
timestamp_min = timestamp_loc(datetime.min)
timestamp_max = timestamp_loc(datetime.max)
def utcoffset(dt):
if dt.tzinfo is None:
return local_tzo(dt)
elif dt.tzinfo is NoTimeZone:
return None
else:
return dt.tzinfo.utcoffset(dt).total_seconds() / 3600
NoTimeZone = timezone(timedelta(0), 'NoTimeZone')
def local_tzo(dt=None):
"""Return the offset between the local time and UTC.
(i.e. return the x of UTC+x).
"""
dt = datetime.now() if dt is None else dt
return (timestamp_loc(dt) - dt.timestamp()) / 3600
## EOF ##
|