Skip to content

dates

This module aims to deal with dates.


The datetime.datetime class is used as internal date type.

dt = datetime.datetime(year=2020, month=12, day=2)

Is equivalent to:

dt = str2datetime("02-12-2020")
dt = str2datetime("2020-12-02")
dt = str2datetime("02/12/2020")

The any2datetime method returns a datetime.datetime instance, whatever the input is (str or datetime.datetime).

dt1 = datetime.datetime(year=2020, month=12, day=2)
dt2 = str2datetime("02-12-2020")
dt1_2 = any2datetime(dt1)  # same
dt2_2 = any2datetime("02-12-2020")  # same

The get_timestamp method converts a datetime.datetime instance into a number of seconds (int).

ts = get_timestamp(dt)  # 1606780800.0

any2datetime(str_or_datetime)

Normalizes the input such as the returned object is a datetime instance.

Parameters:

Name Type Description Default
str_or_datetime Union[str, datetime]

a str (see str2datetime() for supported dates formats) or a datetime

required

Returns:

Type Description
datetime

A datetime instance

Source code in scenes/dates.py
def any2datetime(str_or_datetime: Union[str, datetime]) -> datetime:
    """
    Normalizes the input such as the returned object is a `datetime` instance.

    Args:
        str_or_datetime: a str (see `str2datetime()` for supported dates
            formats) or a `datetime`

    Returns:
        A `datetime` instance

    """
    if isinstance(str_or_datetime, datetime):
        return str_or_datetime
    assert isinstance(str_or_datetime, str), \
        "Date must be a str, or a datetime instance!"
    return str2datetime(str_or_datetime)

get_timestamp(date)

Converts datetime into a timestamp (in seconds)

Parameters:

Name Type Description Default
date datetime

date

required

Returns:

Type Description
int

timestamp (in seconds)

Source code in scenes/dates.py
def get_timestamp(date: datetime) -> int:
    """
    Converts `datetime` into a timestamp (in seconds)

    Args:
        date: date

    Returns:
        timestamp (in seconds)

    """
    return date.replace(tzinfo=timezone.utc).timestamp()

str2datetime(datestr)

Converts an input date as string into a datetime instance.

Parameters:

Name Type Description Default
datestr str

date (str) in any of those formats: - "YYYY-MM-DD" - "DD/MM/YYYY" - "DD-MM-YYYY" - "YYYYMMDD"

required

Returns:

Type Description
datetime

A datetime.datetime instance

Source code in scenes/dates.py
def str2datetime(datestr: str) -> datetime:
    """
    Converts an input date as string into a datetime instance.

    Args:
        datestr: date (str) in any of those formats:
            - "YYYY-MM-DD"
            - "DD/MM/YYYY"
            - "DD-MM-YYYY"
            - "YYYYMMDD"

    Returns:
        A datetime.datetime instance

    """
    # source (with a few enhancements):
    # https://stackoverflow.com/questions/23581128/how-to-format-date-...
    # ...string-via-multiple-formats-in-python
    assert isinstance(datestr, str), "Input must be a str!"
    formats = ('%Y-%m-%d', '%d/%m/%Y', '%d-%m-%Y', '%Y%m%d')
    for fmt in formats:
        try:
            return datetime.strptime(datestr, fmt)
        except ValueError:
            pass
    raise ValueError(
        f'No valid date format found. Accepted formats are {formats}. '
        f'Input was: {datestr}')