Skip to content

Instantly share code, notes, and snippets.

@agebhar1
Created September 7, 2024 09:25
Show Gist options
  • Select an option

  • Save agebhar1/aff6bbb8a94ab4d6989b5615984849d9 to your computer and use it in GitHub Desktop.

Select an option

Save agebhar1/aff6bbb8a94ab4d6989b5615984849d9 to your computer and use it in GitHub Desktop.
Date/Time w/ Python
from datetime import datetime, timezone, time, tzinfo, timedelta
# https://docs.python.org/3/library/datetime.html
def parse(v: str) -> None:
dt = datetime.fromisoformat(v)
print(f" {dt}")
print(f"isoformat : {dt.isoformat(timespec='microseconds')}")
print(f"isoformat(utc): {dt.astimezone(tz=timezone.utc).isoformat(timespec='microseconds')}")
# Return date object with same year, month and day.
print(f"date : {dt.date()}")
# Return time object with same hour, minute, second, microsecond and fold. tzinfo is None. See also method timetz().
print(f"time : {dt.time()}")
# Return time object with same hour, minute, second, microsecond, fold, and tzinfo attributes. See also method time().
print(f"timetz : {dt.timetz()}")
print(f"tzinfo : {dt.tzinfo}")
print(f"utcoffset(sec): {dt.utcoffset().seconds}")
print()
parse('2018-10-28T02:59:59+02:00') # [Europe/Berlin]
parse('2018-10-28T02:00:00+01:00')
assert (datetime.fromisoformat('2018-10-28T02:00:00+01:00') -
datetime.fromisoformat('2018-10-28T02:59:59+02:00')).seconds == 1
assert (datetime.fromisoformat('2018-10-28T01:00:00.000000+00:00') -
datetime.fromisoformat('2018-10-28T00:59:59.000000+00:00')).seconds == 1
assert (datetime.fromisoformat('2019-03-31T03:00:00+02:00') -
datetime.fromisoformat('2019-03-31T01:59:59+01:00')).seconds == 1
print(time.fromisoformat('04:23:01')) # naive
print(time.fromisoformat('T04:23:01')) # naive
print(time.fromisoformat('T04:23:01Z')) # aware
print(time.fromisoformat('T04:23:01+00:00')) # aware
assert time.fromisoformat('04:23:01') != time.fromisoformat('04:23:01+00:00')
assert time.fromisoformat('04:23:01Z') == time.fromisoformat('T04:23:01+00:00')
print(time.fromisoformat('T04:23:01+00:00').replace(tzinfo=timezone(offset=timedelta(hours=1))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment