Metadata-Version: 2.4
Name: tsx
Version: 0.3.4
Summary: TimeStamp eXtensions for Python
Home-page: https://github.com/asuiu/tsx
Author: Andrei Suiu
Author-email: andrei.suiu@gmail.com
License: GPL
Keywords: timestamp time date datetime ISO 8601
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Topic :: System :: Logging
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Internet :: Log Analysis
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: typing-extensions>=3.7.4; python_version < "3.8"
Requires-Dist: python-dateutil>=2.8.2
Requires-Dist: pytz>=2020.1
Requires-Dist: ciso8601>=2.3.1
Requires-Dist: numpy>=1.8.0
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: requires-dist
Dynamic: summary

# tsx

**T**ime **S**tamp e**X**tensions for Python

[![Build Status](https://github.com/asuiu/tsx/actions/workflows/python-package.yml/badge.svg?branch=main)](https://github.com/asuiu/tsx/actions/workflows/python-package.yml)

###### Why tsx?
**tsx** was created as a response to the known Python datetime standard library flaw that violates ISO 8601. ( [Example](https://stackoverflow.com/questions/19654578/python-utc-datetime-objects-iso-format-doesnt-include-z-zulu-or-zero-offset) )

It properly handles the Daylight Saving Time (summer time), and provides functionality for creating, manipulating, and formatting timestamps in various formats
and precisions.

Under the hood, it uses external dateparser library that's fully compatible with ISO 8601, and it simplifies working with date & time stamps.

### Installation

```bash
pip install tsx
```

### Usage:

#### LLM targeted summary: https://github.com/asuiu/tsx/blob/master/LLM-README.md

The library is pretty simple, its central class is `TS`, which inhertis Python builtin `float`,
so every timestamp in fact is a float representing number of seconds since Epoch.

The `TSMsec` is the same `TS` with the only difference that its constructor by default expects millisecond precision, i.e. number
of milliseconds since epoch, while internally it stores a float number of seconds since Epoch.

```python
TS(ts: Union[int, float, str, datetime, date], prec: Literal["s", "ms", "us", "ns"] = "s")

TSMsec(ts: Union[int, float, str, datetime, date], prec: Literal["s", "ms"] = "ms")
```

- `prec` - is precision of the `ts` argument.
    - If `prec=="s"` - the `ts` argument will be interpreted as nr of seconds since epoch,
    - If `prec=="ms"` - the `ts` argument will be interpreted as nr of milliseconds since epoch

### Example:

```python
ts = TS(ts="1519855200.123856", prec="s")

ts == 1519855200.123856
ts.as_iso == '2018-02-28T22:00:00.123856Z'
ts.as_iso_tz(pytz.timezone("Europe/Bucharest")) == '2018-03-01T00:00:00.123856+02:00'

TS("2018-02-28T22:00:00.123Z")
TS("2018-02-28T22:00:00.123")

TS("2018-02-28T22:00:00.123+00:00")
```

```python
ts = TS.now()

ts.as_sec() == 1234567890
ts.as_ms == 1234567890123
ts.as_file_date == '20090213'
ts.as_file_ts == '20090213-233130'
```

## Classes

### `TS`

The TS class, a subclass of float, represents Unix timestamps in seconds. It includes additional methods for timestamp manipulation and formatting.

#### Key Methods and Properties

- `now_dt()`: Returns the current datetime in UTC.
- `now_ms()`, now_us, now_ns: Returns the current timestamp in various precisions.
- `now()`: Returns the current TS instance.
- `from_iso()`: Parses an ISO string to a TS instance.
- `timestamp()`: Returns the timestamp as a TS instance.
- `as_iso()`, `as_iso_date()`, `as_iso_date_basic()`, `as_iso_tz()`, `as_iso_basic()`: Various ISO format representations.
- `as_file_ts()` and `as_file_date()`: File-friendly timestamp formats.
- `as_sec()`, `as_ms()`, `to_sec()`: Conversions to different precisions with deprecation notices.
- `floor()` and `ceil()`: Methods for flooring and ceiling the timestamp.
- `weekday()` and `isoweekday()`: Methods to get the day of the week.
- *Arithmetic Operations*: Overloaded methods for arithmetic, including support for datetime.timedelta and calendar deltas via dTS (months/years).

#### now_dt

- **Description**: Returns the current datetime in UTC.
- **Example**:
  ```python
  current_dt = TS.now_dt()
  current_dt == datetime.datetime(2021, 10, 15, 12, 0, 0, 123456, tzinfo=datetime.timezone.utc)
  ```

#### now

- **Description**: Returns the current timestamp in seconds.
- **Example**:
  ```python
  current_ts = TS.now()
  current_ts == TS(1634294400.123456) == 1634294400.123456
  ```

#### now_ms

- **Description**: Returns the current timestamp in milliseconds.
- **Example**:
  ```python
  current_ts = TS.now_ms()
  current_ts == iTSms(1634294400123) == 1634294400123
  ```

#### now_us

- **Description**: Returns the current timestamp in microseconds.
- **Example**:
  ```python
  current_ts = TS.now_us()
  current_ts == iTSus(1634294400123456) == 1634294400123456
  ```

#### now_ns

- **Description**: Returns the current timestamp in nanoseconds.
- **Example**:
  ```python
  current_ts = TS.now_ns()
  current_ts == iTSn(s1634294400123456789) == 1634294400123456789
  ```

#### from_iso

- **Description**: Parses an ISO string to a TS instance.
- **Example**:
  ```python
  ts = TS.from_iso("2021-10-15T12:00:00.123456Z")
  ts == TS(1634294400.123456) == 1634294400.123456
  ```

#### timestamp

- **Description**: Returns the timestamp as a TS instance.
- **Example**:
  ```python
  ts = TS.timestamp(1634294400.123456)
  ts == TS(1634294400.123456) == 1634294400.123456
  ```

#### as_iso

- **Description**: Returns the timestamp as an ISO string.
- **Example**:
  ```python
  ts = TS(1634294400.123456)
  ts.as_iso == '2021-10-15T12:00:00.123456Z'
  ```

#### as_iso_date

- **Description**: Returns the timestamp as an ISO date string.
- **Example**:
  ```python
  ts = TS(1634294400.123456)
  ts.as_iso_date == '2021-10-15'
  ```

#### as_iso_date_basic

- **Description**: Returns the timestamp as an ISO date string in basic format.
- **Example**:
  ```python
  ts = TS(1634294400.123456)
  ts.as_iso_date_basic == '20211015'
  ```

#### as_iso_tz

- **Description**: Returns the timestamp as an ISO string with timezone.
    - **Parameters**:
        - `tz: str|tzinfo`: The timezone to use.
    - **Example**:
      ```python
      ts = TS(1634294400.123456)
      ts.as_iso_tz(pytz.timezone("Europe/Bucharest")) == '2021-10-15T14:00:00.123456+02:00'
      ```

#### as_iso_basic

- **Description**: Returns the timestamp as an ISO string in basic format.
- **Example**:
  ```python
  ts = TS(1634294400.123456)
  ts.as_iso_basic == '20211015T120000.123456Z'
  ```

#### as_file_ts

- **Description**: Returns the timestamp as a file-friendly timestamp string.
- **Example**:
  ```python
  ts = TS(1634294400.123456)
  ts.as_file_ts == '20211015-120000'
  ```

#### as_file_date

- **Description**: Returns the timestamp as a file-friendly date string.
- **Example**:
  ```python
  ts = TS(1634294400.123456)
  ts.as_file_date == '20211015'
  ```

#### as_sec

- **Description**: Returns the timestamp as a TS instance in seconds.
- **Example**:
  ```python
  ts = TS(1634294400.123456)
  ts.as_sec() == iTS(1634294400) == 1634294400
  ```

#### as_ms

- **Description**: Returns the timestamp as a TS instance in milliseconds.
- **Example**:
  ```python
  ts = TS(1634294400.123456)
  ts.as_ms == iTSms(1634294400123) == 1634294400123
  ```

#### to_sec

- **Description**: Returns the timestamp as a TS instance in seconds.
- **Example**:
  ```python
  ts = TS(1634294400.123456)
  ts.to_sec == TS(1634294400.0) == 1634294400.0
  ```

#### floor

- **Description**: Floors the timestamp to the nearest second.
    - **Parameters**:
        - `unit: int|float`: the unit to ceil which should be of the same precision as the timestamp
- **Example**:
  ```python
  ts = TS(1634294413.123456)
  ts.floor(100) == TS(1634294400.0) == 1634294400.0

  ts.floor(0.025) == TS(1634294413.1) == 1634294400.1
  ```

#### ceil

- **Description**: Ceils the timestamp to the nearest second.
    - **Parameters**:
        - `unit: int|float`: the unit to ceil which should be of the same precision as the timestamp
    - **Example**:
      ```python
      ts = TS(1634294413.123456)
      ts.ceil(100) == TS(1634294500.0) == 1634294500.0

      ts.ceil(0.025) == TS(1634294413.125) == 1634294500.125
      ```

#### weekday

- **Description**: Return the day of the week as an integer, where Monday is 0 and Sunday is 6. See also isoweekday().
    - **Parameters**:
        - `utc: bool = True`: Whether to use UTC or local time.
    - **Example**:
      ```python
      ts = TS(1634294400.123456)
      ts.weekday() == 4
      ```

- **Description**: Return the day of the week as an integer, where Monday is 1 and Sunday is 7. See also weekday().
    - **Parameters**:
        - `utc: bool = True`: Whether to use UTC or local time.
    - **Example**:
      ```python
      ts = TS(1634294400.123456)
      ts.isoweekday() == 5
      ```

#### Arithmetic Operations

- **Description**: Overloaded methods for arithmetic including datetime.timedelta and dTS support.
    - **Parameters**:
        - `other: Union[int, float, datetime.timedelta, dTS]`
    - **Examples**:
      ```python
      from datetime import timedelta
      from tsx.ts import dTS

      ts = TS(1634294400.123456)
      ts + 100                          # add seconds
      ts + timedelta(milliseconds=250)  # add timedelta
      ts + dTS("2M")                    # add 2 calendar months
      ```

### `TSMsec`

The TSMsec class, a subclass of float, and it's used as a factory class to instantiate TS from milliseconds precision.

After instantiation, the TSMsec instance is identical to TS instance, and it includes all the same methods and properties.

### `iTS`

- The iTS class, a subclass of int, represents Unix timestamps in seconds. It includes additional methods for timestamp manipulation and formatting.
- It inherits from `BaseTS` and `int` classes, so it exposes all the methods `TS` has, as well as it supports all the arithmetic operations `int` supports.
- It's identical to `TS` class, but all the methods that return `TS` will return `iTS` instead, excepting the timestamp(), which returns `TS`.

#### Key Methods and Properties

- The same as `TS` class, but all the methods that return `TS` will return `iTS` instead.

### `iTSms`

- The iTSms class, a subclass of int, represents Unix timestamps in milliseconds. It includes additional methods for timestamp manipulation and formatting.
- It inherits from `BaseTS` and `int` classes, so it exposes all the methods `TS` has, as well as it supports all the arithmetic operations `int` supports.
- It's identical to `TSMsec` class, but all the methods that return `TS` will return `iTSms` instead, excepting the timestamp(), which returns `TS`.

### `iTSus`

- The iTSus class, a subclass of int, represents Unix timestamps in microseconds. It includes additional methods for timestamp manipulation and formatting.
- It inherits from `BaseTS` and `int` classes, so it exposes all the methods `TS` has, as well as it supports all the arithmetic operations `int` supports.
- It's identical to `TS` class, but all the methods that are expected to return `TS` will return `iTSus` instead, excepting the timestamp(), which returns `TS`.

### `iTSns`

- The iTSns class, a subclass of int, represents Unix timestamps in nanoseconds. It includes additional methods for timestamp manipulation and formatting.
- It inherits from `BaseTS` and `int` classes, so it exposes all the methods `TS` has, as well as it supports all the arithmetic operations `int` supports.
- It's identical to `TS` class, but all the methods that are expected to return `TS` will return `iTSns` instead, excepting the timestamp(), which returns `TS`.
- **Note**: `iTSns` supports nanosecond values for storage/formatting/arithmetics (timedelta limited to microsecond resolution). ISO formatting prints nanoseconds and appends `Z`.

### `dTS`

`dTS` is an immutable duration with both fixed and calendar components. It supports the existing compact/scalar interface, Python `timedelta`, and timedelta-style keyword arguments extended with integer `months` and `years`:

```python
from datetime import timedelta
from tsx.ts import dTS

dTS("7d")
dTS(7, unit="d")
dTS(timedelta(days=7, seconds=30))
dTS(weeks=1, hours=2, microseconds=3)
dTS(years=1, months=2)
dTS(months=1, days=2)  # calendar adjustment, then fixed-duration adjustment
```

The positional `delta/unit` form and component keyword form cannot be mixed. Calendar months and years must be integers. All timestamp classes support `timestamp + delta`, `delta + timestamp`, and `timestamp - delta`, preserving the timestamp class and its native precision.

### Changelog

See the complete release history in [CHANGELOG.md](CHANGELOG.md).
