-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
28 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,21 +1,47 @@ | ||
""" | ||
Utility functions for working with datetimes in UTC format. | ||
This module provides custom versions of common datetime operations to ensure | ||
returned datetimes are always in the UTC timezone and are not naive. | ||
The main goal is to prevent potential issues related to timezone-aware and | ||
timezone-naive datetime objects. | ||
""" | ||
from datetime import datetime, timezone | ||
|
||
|
||
def now(): | ||
def now() -> datetime: | ||
""" | ||
Customized version of `datetime.datetime.now` to ensure | ||
UTC timezone and format. | ||
Returns | ||
------- | ||
datetime | ||
Current UTC datetime with hour, minute, second, and microsecond set to 0. | ||
This datetime is timezone-aware and is not naive. | ||
""" | ||
utc_dt = datetime.now(timezone.utc).replace( | ||
hour=0, minute=0, second=0, microsecond=0 | ||
) | ||
return utc_dt | ||
|
||
|
||
def fromtimestamp(timestamp): | ||
def fromtimestamp(timestamp: int) -> datetime: | ||
""" | ||
Customized version of `datetime.datetime.fromtimestamp` to ensure | ||
UTC timezone and format. | ||
Parameters | ||
---------- | ||
timestamp : int | ||
Unix timestamp to be converted to datetime. | ||
Returns | ||
------- | ||
datetime | ||
The UTC datetime representation of the given timestamp. | ||
This datetime is timezone-aware and is not naive. | ||
""" | ||
utc_timestamp = datetime.fromtimestamp(timestamp, tz=timezone.utc) | ||
return utc_timestamp |