Skip to content

Date Time



Timezone

Format datetime to ISO 8601

from datetime import datetime
from dateutil import tz

# Create time without TZ, you cannot print out the "offset", i.e. +09:00
new_dt = datetime.now()
new_dt.isoformat(timespec="seconds")
# '2022-06-03T15:56:27'

TZJP = tz.gettz('Asia/Tokyo')
new_dt = datetime.now(tz=TZJP)
new_dt.isoformat(timespec="seconds")
# '2022-06-03T15:57:00+09:00'

Revise the TZ info to naive time

from dateutil import tz
from datetime import datetime

# tzinfo instance
TZJP = tz.gettz('Asia/Tokyo')

# Convert datetime var to string, in ISO 8601 format with timezone value
def convert_datetime_to_iso_8601(dt: datetime) -> str:
    new_dt = dt
    # If no timezone provided, set it to JPT
    if dt.tzinfo is None:
        new_dt = new_dt.replace(tzinfo=TZJP)
    # So it return datetime in this ISO format: 2022-05-18T13:24:28+09:00
    return new_dt.isoformat(timespec="seconds")

Formating

from dateutil import tz
from datetime import datetime
TZJP = tz.gettz('Asia/Tokyo')

a = datetime.now(tz=TZJP)
print(a.isoformat(timespec="seconds"))
# 2022-05-18T13:24:28+09:00
print(a.strftime('%Y-%m-%dT%H:%M:%S%z'))
# 2022-05-18T13:24:28+0900

Elapse Time / Benchmark

https://realpython.com/python-timer/

By native time package

import time

tic = time.perf_counter()
tutorial = feed.get_article(0)
toc = time.perf_counter()
print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")

Customized ContextManager

from time import time

# Use as context manager to report time easily
# Usage:
#       with TimerManager("Example long waiting task", callback=logger.warning):
#           sleep(5)
class TimerManager(object):
    def __init__(self, description, *args, callback=None):
        self.description = description
        if callback:
            self.callback = callback

    def __enter__(self):
        self.start = time()
        self._print_out(f"{self.description} start now...")

    def __exit__(self, type, value, traceback):
        self.end = time()
        self._print_out(f"{self.description} finished, time elapsed: {self.end - self.start:0.4f}s")

    def _print_out(self, content):
        if callable(self.callback):
            self.callback(content)
        else:
            print(content)

Comments