Python Datetime Time

A datetime.time object represents a time.


Usage

A datetime.time object is constructed as:

t1 = datetime.time(23, 59, 59, 999999, tzinfo=None)

All arguments are optional.

t2 = datetime.time()

The components can be accessed like:

t1.hour         # 23
t1.minute       # 59
t1.second       # 59
t1.millisecond  # 999999
t1.tzinfo       # None
t1.fold         # 0

Note that fold is used to indicate a time that is 'repeated' (as in 'setting the clock back').


Class Functions

FromIsoFormat

To construct a datetime.time from most valid ISO 8601 strings, try:

import datetime

datetime.time.fromisoformat('04:23:01')   #datetime.time(4, 23, 1)
datetime.time.fromisoformat('T04:23:01')  #datetime.time(4, 23, 1)
datetime.time.fromisoformat('T042301')    #datetime.time(4, 23, 1)
datetime.time.fromisoformat('04:23:01Z')  #datetime.time(4, 23, 1, tzinfo=datetime.timezone.utc)
  1. The T prefix is not required
  2. Timezone offsets are allowed to have fractional seconds
  3. Hours and minutes are not allowed to be fractional
  4. Seconds are allowed to be fractional to any number of digits


Methods

Dst

A passthrough to datetime.timezone.dst for the tzinfo component of datetime.time.

If the datetime.time object is timezone naive, returns None.


IsoFormat

Return a string like HH:MM:SS. Appends microseconds like .ffffff if not 0. Appends timezone offset like +HH:MM[:SS[.ffffff]] if not timezone naive.

An optional keyword-only argument timespec customizes the string.


Replace

Return a copy of the datetime.time object with the specified components replaced.

import datetime

t1 = datetime.time(23, 59, 59, 999999, tzinfo=datetime.timezone.utc)
t2 = t1.replace(tzinfo=None)
t3 = t2.replace(hour=0)


StrFTime

Return a formatted string timestamp.

See here for an explanation of the directives.


TzName

A passthrough to datetime.timezone.tzname for the tzinfo component of datetime.time.

If the datetime.time object is timezone naive, returns None.


UtcOffset

A passthrough to datetime.timezone.utcoffset for the tzinfo component of datetime.time.

If the datetime.time object is timezone naive, returns None.


Operations

datetime.time objects can be used with the following operators.

Operation

Meaning

t1 < t2

returns True if t1 is earlier than t2 else False

t1 == t2

returns True if t1 represents the same UTC or timezone naive time as t2 else False

Two datetime.time objects can only be compared if both have timezone information, or both are naive to timezones. Mixing categories will raise a TypeError, except for the == and != operators (which will always indicate that the two are unlike).


CategoryRicottone

Python/Datetime/Time (last edited 2023-04-12 15:18:01 by DominicRicottone)