File: time.py

package info (click to toggle)
python-fs 2.4.16-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,944 kB
  • sloc: python: 13,048; makefile: 226; sh: 3
file content (43 lines) | stat: -rw-r--r-- 870 bytes parent folder | download | duplicates (2)
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
"""Time related tools.
"""

from __future__ import print_function, unicode_literals

import typing

from calendar import timegm
from datetime import datetime

try:
    from datetime import timezone
except ImportError:
    from ._tzcompat import timezone  # type: ignore

if typing.TYPE_CHECKING:
    from typing import Optional


def datetime_to_epoch(d):
    # type: (datetime) -> int
    """Convert datetime to epoch."""
    return timegm(d.utctimetuple())


@typing.overload
def epoch_to_datetime(t):  # noqa: D103
    # type: (None) -> None
    pass


@typing.overload
def epoch_to_datetime(t):  # noqa: D103
    # type: (int) -> datetime
    pass


def epoch_to_datetime(t):
    # type: (Optional[int]) -> Optional[datetime]
    """Convert epoch time to a UTC datetime."""
    if t is None:
        return None
    return datetime.fromtimestamp(t, tz=timezone.utc)