Skip to content

Datetime

laktory.datetime.unix_timestamp ¤

unix_timestamp(dt=None, unit='s', as_int=False)

Convert a datetime object into a unix timestamp float. If None is provided, current UTC timestamp is returned.

PARAMETER DESCRIPTION
dt

Datetime object

TYPE: Union[str, int, float, datetime, date] DEFAULT: None

RETURNS DESCRIPTION
output

Unix timestamp

TYPE: float

Examples:

from laktory.datetime import unix_timestamp
from datetime import datetime

ts = unix_timestamp("2020-01-01T01:00:00")
print(ts)
# > 1577840400.0

ts = unix_timestamp(datetime(2020, 1, 1, 1, 0, 0))
print(ts)
# > 1577840400.0
Source code in laktory/datetime.py
 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
def unix_timestamp(
    dt: Union[str, int, float, datetime, date] = None,
    unit: str = "s",
    as_int: bool = False,
) -> float:
    """
    Convert a datetime object into a unix timestamp float. If `None` is provided,
    current UTC timestamp is returned.

    Parameters
    ----------
    dt:
        Datetime object

    Returns
    -------
    output:
        Unix timestamp

    Examples
    --------
    ```py
    from laktory.datetime import unix_timestamp
    from datetime import datetime

    ts = unix_timestamp("2020-01-01T01:00:00")
    print(ts)
    # > 1577840400.0

    ts = unix_timestamp(datetime(2020, 1, 1, 1, 0, 0))
    print(ts)
    # > 1577840400.0
    ```
    """

    numeric_types = [int, float]
    np_installed = False
    np = None
    try:
        import numpy as np

        np_installed = True
        numeric_types += [np.float64, np.int64]
    except ModuleNotFoundError:
        pass

    if dt is None:
        dt = datetime.utcnow()
    elif type(dt) in numeric_types:
        dt = dt
    elif type(dt) == date:  # noqa: E721
        dt = datetime.combine(dt, datetime.min.time())
    elif isinstance(dt, str):
        try:
            dt = datetime.fromisoformat(dt)
        except ValueError:
            try:
                from dateutil import parser

                dt = parser.parse(dt)
            except ModuleNotFoundError:
                raise ValueError(
                    f"String '{dt}' is not a valid ISO 8601 datetime format. Install `dateutil` to support other formats."
                )
    elif np_installed and isinstance(dt, np.datetime64):
        dt = dt.astype(datetime)
        if isinstance(dt, int):
            dt = dt * units["ns"]["s"]

    if isinstance(dt, datetime) or isinstance(dt, date):
        # if pd.isnull(dt):
        #     dt = np.nan
        # else:
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=timezone.utc)
        dt = dt.timestamp()

    # Set units
    dt *= units["s"][unit]

    # Set type
    if as_int:
        dt = int(dt)

    return dt

laktory.datetime.utc_datetime ¤

utc_datetime(unixtime=None)

Convert a unix timestamp into a datetime object. If None is provided, current UTC datetime object is returned.

PARAMETER DESCRIPTION
unixtime

Unix timestamp

TYPE: Union[datetime, date, str, float, int] DEFAULT: None

RETURNS DESCRIPTION
output

Datetime object

TYPE: datetime

Examples:

from laktory.datetime import utc_datetime

dt = utc_datetime("2020-01-01T01:00:00")
print(dt)
# > 2020-01-01 01:00:00

dt = utc_datetime(1577840400)
print(dt)
# > 2020-01-01 01:00:00
Source code in laktory/datetime.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def utc_datetime(
    unixtime: Union[datetime, date, str, float, int] = None,
) -> datetime:
    """
    Convert a unix timestamp into a datetime object. If `None` is provided,
    current UTC datetime object is returned.

    Parameters
    ----------
    unixtime:
        Unix timestamp

    Returns
    -------
    output:
        Datetime object

    Examples
    --------
    ```py
    from laktory.datetime import utc_datetime

    dt = utc_datetime("2020-01-01T01:00:00")
    print(dt)
    # > 2020-01-01 01:00:00

    dt = utc_datetime(1577840400)
    print(dt)
    # > 2020-01-01 01:00:00
    ```
    """

    np_installed = False
    np = None
    try:
        import numpy as np

        np_installed = True
    except ModuleNotFoundError:
        pass

    if not unixtime:
        dt = datetime.utcnow()
    elif isinstance(unixtime, datetime):
        dt = unixtime
    elif isinstance(unixtime, date):
        dt = datetime.combine(unixtime, datetime.min.time())
    elif isinstance(unixtime, str):
        dt = datetime.fromisoformat(unixtime)
    elif np_installed and np.isnan(unixtime):
        dt = None
    else:
        dt = datetime.fromtimestamp(unixtime, tz=timezone.utc).replace(tzinfo=None)

    return dt