Timestamp
class
TimestampStyles (str, Enum)
¶
An enumeration.
Source code in naff/models/discord/timestamp.py
class TimestampStyles(str, Enum):
ShortTime = "t"
LongTime = "T"
ShortDate = "d"
LongDate = "D"
ShortDateTime = "f" # default
LongDateTime = "F"
RelativeTime = "R"
class
Timestamp (datetime)
¶
A special class that represents Discord timestamps.
Assumes that all naive datetimes are based on local timezone.
Source code in naff/models/discord/timestamp.py
class Timestamp(datetime):
"""
A special class that represents Discord timestamps.
Assumes that all naive datetimes are based on local timezone.
"""
@classmethod
def fromdatetime(cls, dt: datetime) -> "Timestamp":
"""Construct a timezone-aware UTC datetime from a datetime object."""
timestamp = cls.fromtimestamp(dt.timestamp(), tz=dt.tzinfo)
if timestamp.tzinfo is None: # assume naive datetimes are based on local timezone
return timestamp.astimezone()
return timestamp
@classmethod
def utcfromtimestamp(cls, t: float) -> "Timestamp":
"""Construct a timezone-aware UTC datetime from a POSIX timestamp."""
return super().utcfromtimestamp(t).replace(tzinfo=timezone.utc)
@classmethod
def fromisoformat(cls, date_string: str) -> "Timestamp":
timestamp = super().fromisoformat(date_string)
if timestamp.tzinfo is None: # assume naive datetimes are based on local timezone
return timestamp.astimezone()
return timestamp
@classmethod
def fromisocalendar(cls, year: int, week: int, day: int) -> "Timestamp":
return super().fromisocalendar(year, week, day).astimezone()
@classmethod
def fromtimestamp(cls, t: float, tz=None) -> "Timestamp":
try:
timestamp = super().fromtimestamp(t, tz=tz)
except Exception:
# May be in milliseconds instead of seconds
timestamp = super().fromtimestamp(t / 1000, tz=tz)
if timestamp.tzinfo is None: # assume naive datetimes are based on local timezone
return timestamp.astimezone()
return timestamp
@classmethod
def fromordinal(cls, n: int) -> "Timestamp":
return super().fromordinal(n).astimezone()
@classmethod
def now(cls, tz=None) -> "Timestamp":
"""
Construct a datetime from time.time() and optional time zone info.
If no timezone is provided, the time is assumed to be from the computer's
local timezone.
"""
t = time.time()
return cls.fromtimestamp(t, tz)
@classmethod
def utcnow(cls) -> "Timestamp":
"""Construct a timezone-aware UTC datetime from time.time()."""
t = time.time()
return cls.utcfromtimestamp(t)
def to_snowflake(self, high: bool = False) -> Union[str, int]:
"""
Returns a numeric snowflake pretending to be created at the given date.
When using as the lower end of a range, use ``tosnowflake(high=False) - 1``
to be inclusive, ``high=True`` to be exclusive.
When using as the higher end of a range, use ``tosnowflake(high=True) + 1``
to be inclusive, ``high=False`` to be exclusive
"""
discord_millis = int(self.timestamp() * 1000 - DISCORD_EPOCH)
return (discord_millis << 22) + (2**22 - 1 if high else 0)
@classmethod
def from_snowflake(cls, snowflake: "Snowflake_Type") -> "Timestamp":
"""
Construct a timezone-aware UTC datetime from a snowflake.
Args:
snowflake: The snowflake to convert.
Returns:
A timezone-aware UTC datetime.
??? Info
https://discord.com/developers/docs/reference#convert-snowflake-to-datetime
"""
if isinstance(snowflake, str):
snowflake = int(snowflake)
timestamp = ((snowflake >> 22) + DISCORD_EPOCH) / 1000
return cls.utcfromtimestamp(timestamp)
def format(self, style: Optional[Union[TimestampStyles, str]] = None) -> str:
"""
Format the timestamp for discord client to display.
Args:
style: The style to format the timestamp with.
Returns:
The formatted timestamp.
"""
if not style:
return f"<t:{self.timestamp():.0f}>"
else:
return f"<t:{self.timestamp():.0f}:{style}>"
def __str__(self) -> str:
return self.format()
classmethod
method
fromdatetime(dt)
¶
Construct a timezone-aware UTC datetime from a datetime object.
Source code in naff/models/discord/timestamp.py
@classmethod
def fromdatetime(cls, dt: datetime) -> "Timestamp":
"""Construct a timezone-aware UTC datetime from a datetime object."""
timestamp = cls.fromtimestamp(dt.timestamp(), tz=dt.tzinfo)
if timestamp.tzinfo is None: # assume naive datetimes are based on local timezone
return timestamp.astimezone()
return timestamp
classmethod
method
utcfromtimestamp(t)
¶
Construct a timezone-aware UTC datetime from a POSIX timestamp.
Source code in naff/models/discord/timestamp.py
@classmethod
def utcfromtimestamp(cls, t: float) -> "Timestamp":
"""Construct a timezone-aware UTC datetime from a POSIX timestamp."""
return super().utcfromtimestamp(t).replace(tzinfo=timezone.utc)
classmethod
method
fromisoformat(date_string)
¶
string -> datetime from datetime.isoformat() output
Source code in naff/models/discord/timestamp.py
@classmethod
def fromisoformat(cls, date_string: str) -> "Timestamp":
timestamp = super().fromisoformat(date_string)
if timestamp.tzinfo is None: # assume naive datetimes are based on local timezone
return timestamp.astimezone()
return timestamp
classmethod
method
fromisocalendar(year, week, day)
¶
int, int, int -> Construct a date from the ISO year, week number and weekday.
This is the inverse of the date.isocalendar() function
Source code in naff/models/discord/timestamp.py
@classmethod
def fromisocalendar(cls, year: int, week: int, day: int) -> "Timestamp":
return super().fromisocalendar(year, week, day).astimezone()
classmethod
method
fromtimestamp(t, tz)
¶
timestamp[, tz] -> tz's local time from POSIX timestamp.
Source code in naff/models/discord/timestamp.py
@classmethod
def fromtimestamp(cls, t: float, tz=None) -> "Timestamp":
try:
timestamp = super().fromtimestamp(t, tz=tz)
except Exception:
# May be in milliseconds instead of seconds
timestamp = super().fromtimestamp(t / 1000, tz=tz)
if timestamp.tzinfo is None: # assume naive datetimes are based on local timezone
return timestamp.astimezone()
return timestamp
classmethod
method
fromordinal(n)
¶
int -> date corresponding to a proleptic Gregorian ordinal.
Source code in naff/models/discord/timestamp.py
@classmethod
def fromordinal(cls, n: int) -> "Timestamp":
return super().fromordinal(n).astimezone()
classmethod
method
now(tz)
¶
Construct a datetime from time.time() and optional time zone info.
If no timezone is provided, the time is assumed to be from the computer's local timezone.
Source code in naff/models/discord/timestamp.py
@classmethod
def now(cls, tz=None) -> "Timestamp":
"""
Construct a datetime from time.time() and optional time zone info.
If no timezone is provided, the time is assumed to be from the computer's
local timezone.
"""
t = time.time()
return cls.fromtimestamp(t, tz)
classmethod
method
utcnow()
¶
Construct a timezone-aware UTC datetime from time.time().
Source code in naff/models/discord/timestamp.py
@classmethod
def utcnow(cls) -> "Timestamp":
"""Construct a timezone-aware UTC datetime from time.time()."""
t = time.time()
return cls.utcfromtimestamp(t)
method
to_snowflake(self, high)
¶
Returns a numeric snowflake pretending to be created at the given date.
When using as the lower end of a range, use tosnowflake(high=False) - 1
to be inclusive, high=True
to be exclusive.
When using as the higher end of a range, use tosnowflake(high=True) + 1
to be inclusive, high=False
to be exclusive
Source code in naff/models/discord/timestamp.py
def to_snowflake(self, high: bool = False) -> Union[str, int]:
"""
Returns a numeric snowflake pretending to be created at the given date.
When using as the lower end of a range, use ``tosnowflake(high=False) - 1``
to be inclusive, ``high=True`` to be exclusive.
When using as the higher end of a range, use ``tosnowflake(high=True) + 1``
to be inclusive, ``high=False`` to be exclusive
"""
discord_millis = int(self.timestamp() * 1000 - DISCORD_EPOCH)
return (discord_millis << 22) + (2**22 - 1 if high else 0)
classmethod
method
from_snowflake(snowflake)
¶
Construct a timezone-aware UTC datetime from a snowflake.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
snowflake |
Snowflake_Type |
The snowflake to convert. |
required |
Returns:
Type | Description |
---|---|
Timestamp |
A timezone-aware UTC datetime. |
Info
https://discord.com/developers/docs/reference#convert-snowflake-to-datetime
Source code in naff/models/discord/timestamp.py
@classmethod
def from_snowflake(cls, snowflake: "Snowflake_Type") -> "Timestamp":
"""
Construct a timezone-aware UTC datetime from a snowflake.
Args:
snowflake: The snowflake to convert.
Returns:
A timezone-aware UTC datetime.
??? Info
https://discord.com/developers/docs/reference#convert-snowflake-to-datetime
"""
if isinstance(snowflake, str):
snowflake = int(snowflake)
timestamp = ((snowflake >> 22) + DISCORD_EPOCH) / 1000
return cls.utcfromtimestamp(timestamp)
method
format(self, style)
¶
Format the timestamp for discord client to display.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
style |
Union[naff.models.discord.timestamp.TimestampStyles, str] |
The style to format the timestamp with. |
None |
Returns:
Type | Description |
---|---|
str |
The formatted timestamp. |
Source code in naff/models/discord/timestamp.py
def format(self, style: Optional[Union[TimestampStyles, str]] = None) -> str:
"""
Format the timestamp for discord client to display.
Args:
style: The style to format the timestamp with.
Returns:
The formatted timestamp.
"""
if not style:
return f"<t:{self.timestamp():.0f}>"
else:
return f"<t:{self.timestamp():.0f}:{style}>"