Python has a number of built-in APIs for manipulating time, which are distributed in standard libraries such as time and datetime, and their usage can be confusing.

The following article will introduce the main purpose, core objects, common methods, and uses of each module, and will end with an analysis and comparison, so if you already know these details, you can jump directly to the summary and comparison section at the end.

In addition, this article will avoid more complex and in-depth topics such as string formatting, time zones, winter and summer time, etc.

time module

In a nutshell, the time module gets the total number of seconds (possibly floating point) elapsed since the epoch, which is often referred to as the POSIX timestamp, from the system’s underlying timer. This is a lower-order usage, suitable for precise timing. For Unix systems, epoch is January 1, 1970 00:00:00 (UTC), so this module can also convert timestamps to specific datetime, but the structure of the object representing datetime is very simple and not suitable for complex operations and representations.

Core objects

The time module has only one class in its API: time.struct_time.

struct_time is a structured time object obtained by converting the number of seconds elapsed since epoch, and it provides an API similar to namedtuple to get the year, month, day, hour, minute, and second properties of an object by subscript or attribute name. Calling gmtime() , localtime() , strptime() and so on can get struct_time instances.

1
2
3
4
5
6
7
>>> st = time.localtime()
>>> st
time.struct_time(tm_year=2021, tm_mon=4, tm_mday=29, tm_hour=12, tm_min=39, tm_sec=14, tm_wday=3, tm_yday=119, tm_isdst=0)
>>> st.tm_mon
4
>>> st[1]
4

As you can see from the example, the struct_time instance is essentially a sequence of numeric class ancestors, and the functions in the module that receive the struct_time instance as an argument can all receive an ancestor of the same length directly. It can simply record the year, month, day, hour and minute properties obtained by converting the timestamp, and provides no other methods to support additional operations, so its use in practice is very limited.

1
2
3
4
5
6
7
>>> st1 = time.localtime()
>>> st2 = time.localtime()
>>> st2 - st1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    st2 - st1
TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'time.struct_time

Common uses and functions

  1. Timing

    • time.time() returns the number of seconds that have elapsed since epoch as a floating point number. Common usage is to derive the program execution time by counting the interval between two calls.

      1
      2
      
      >>> time.time()
      1619665423.683973
      
    • time.sleep(seconds) pauses the execution of the calling thread for a given number of seconds. Often used in test simulations, where the actual pause time may exceed the given number of seconds.

    • time.perf_counter() is a better way to calculate shorter intervals, with more accurate results, and can replace time.time() above when calculating execution times.

      1
      2
      3
      4
      
      >>> start = time.perf_counter()
      >>> end = time.perf_counter()
      >>> end - start
      2.731515233999744
      
  2. Convert between struct_time and timestamp

    • time.gmtime([secs]) converts the given number of seconds to a UTC time zone struct_time object, or uses the return value obtained from time.time() if no seconds are provided.

      1
      2
      3
      4
      5
      
      >>> now = time.time()
      >>> time.gmtime(now)
      time.struct_time(tm_year=2021, tm_mon=4, tm_mday=29, tm_hour=4, tm_min=51, tm_sec=54, tm_wday=3, tm_yday=119, tm_isdst=0)
      >>> time.gmtime()
      time.struct_time(tm_year=2021, tm_mon=4, tm_mday=29, tm_hour=4, tm_min=51, tm_sec=56, tm_wday=3, tm_yday=119, tm_isdst=0)
      
    • time.localtime([secs]) converts the given number of seconds to a struct_time object in the local time zone, or uses the return value from time.time() if no seconds are provided.

      1
      2
      
      >>> time.localtime()
      time.struct_time(tm_year=2021, tm_mon=4, tm_mday=29, tm_hour=12, tm_min=53, tm_sec=38, tm_wday=3, tm_yday=119, tm_isdst=0)
      
    • time.mktime(t) converts a struct_time object to seconds, which will be treated as a local time zone, with exactly the opposite effect of time.localtime([secs]).

      1
      2
      
      >>> time.mktime(time.localtime())
      1619672313.0
      
  3. Convert between struct_time and a string

    • time.strftime(format[, t]) formats a struct_time object to a string in the specified format encoding, and the default value of t is the return value of time.localtime().

      1
      2
      
      >>> time.strftime('%H:%M:%S')
      '13:10:37'
      
    • time.strptime(string[, format] parses a string into a struct_time object with the specified format encoding, the default value of format is "%a %b %d %H:%M:%S %Y".

      1
      2
      3
      
      >>> time.strptime("30 Nov 00", "%d %b %y")   
      time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
                      tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
      

      As in the example above, time units not provided at the time of parsing will be filled with default values.

datetime module

The datetime module supports date and time operations, but the focus of the implementation is to provide efficient property extraction for output formatting and manipulation.

The datetime module provides a number of classes for manipulating dates and times. The vast majority of the module’s functionality revolves around the methods and properties of the following 4 classes (and two additional classes on time zones). One confusing point is that although they are all Python classes, the naming convention of initial capitalization is not followed, and they look like sub-packages or sub-modules under datetime when imported.

We’ll briefly describe each class’s common instance construction, supported operators, instance methods, and instance properties.

date

Indicates the date type.

Instance construction method

  • Instantiates the date class by passing in the year, month, and day parameters corresponding to the date.

    1
    2
    
    >>> date(2021, 4, 29)
    datetime.date(2021, 4, 29)
    
  • The date.fromtimestamp(timestamp) class method is called with the number of seconds since epoch obtained via the time module (i.e., the timestamp).

    1
    2
    
    >>> date.fromtimestamp(time.time())
    datetime.date(2021, 4, 29)
    
  • Calling the date.today() class method, which is essentially calling the date.fromtimestamp() class method with the current timestamp as an argument.

  • Calling the date.fromisoformat(date_string) class method, which is a more intuitive way to create.

    1
    2
    
    >>> date.fromisoformat('2021-04-29')
    datetime.date(2021, 4, 29)
    

Supported Operators

  • Supports comparison operations such as == , , < , , > with another date object.
  • Supports adding and subtracting from a timedelta object, the result is still a date object.
  • Supports subtracting from another date object to get a timedelta object.
  • Hashing is supported.

Instance Methods

  • strftime(self, fmt) Returns a string representation of the current date object in the specified fmt formatting code.

    1
    2
    3
    
    >>> d1 = date.today()
    >>> d1.strftime('%Y-%m-%d')
    '2021-04-29'
    
  • isoformat(self) returns the iso string representation of the current date object.

    1
    2
    
    >>> d1.isoformat()
    '2021-04-29'
    
  • timetuple(self) converts the current date object to the time module’s struct_time object and returns it, with attributes such as hours, minutes and seconds filled in using the default values.

    1
    2
    
    >>> d1.timetuple()
    time.struct_time(tm_year=2021, tm_mon=4, tm_mday=29, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=119, tm_isdst=-1)
    
  • replace(self, year=None, month=None, day=None) returns a copy of the current date object after replacing one of its attributes.

    1
    2
    
    >>> d1.replace(day=30)
    datetime.date(2021, 4, 30)
    
  • weekday(self) returns the week to which the current date object belongs, starting from 0.

    1
    2
    
    >>> d1.weekday()
    3
    

Instance Properties

  • year
  • month
  • day

time

Indicates the time (hour, minute, and second) type.

Instance construction method

time does not support constructing instances by timestamp.

  • Instantiate the time class and pass in the corresponding parameters. You need to pass the parameters corresponding to the time in hours, minutes, seconds, microseconds, etc. The parameters have a range of values and the default value is 0.

    1
    2
    
    >>> date(2021, 4, 29)
    datetime.date(2021, 4, 29)
    
  • Create an instance from the iso string by calling the fromisoformat(cls, time_string) class method.

    1
    2
    
    >>> time.fromisoformat('17:32:10')
    datetime.time(17, 32, 10)
    

Supported Operators

  • Supports comparison operations such as == , , < , , > with another time object.
  • Hashing is supported.

If we want to calculate the time interval between two time objects, we can use datetime.combine() to process them into datetime objects with the same date and then calculate them:

1
2
>>> datetime.combine(date.today(), t2) - datetime.combine(date.today(), t1) 
datetime.timedelta(seconds=4440)

Instance Methods

  • strftime(self, fmt) Returns a string representation of the current time object in the specified fmt formatting code.

    1
    2
    3
    
    >>> t = time.fromisoformat('17:32:10')
    >>> t.strftime('%Hh %Mm %Ss')
    '17h 32m 10s'
    
  • isoformat(self) returns the iso string representation of the current time object.

    1
    2
    3
    
    >>> t = time(hour=17, minute=27, second=55)
    >>> t.isoformat()
    '17:27:55'
    
  • replace(self,hour=None,minute=None,second=None,microsecond=None, tzinfo=True, *,fold=None) Returns a copy of the current time object after replacing one of its attributes.

1
2
>>> t.replace(hour=20)
datetime.time(20, 27, 55)

Instance Properties

  • hour
  • minute
  • second
  • and properties like micorsecond, tzinfo, fold, etc.

datetime

is a subclass of date and therefore inherits all the properties and methods of date. Its instance can also be treated as a combination of date and time instances, and thus has most of the methods and properties of both objects.

The methods and properties inherited from date are not included in the following description.

Instance construction method

  • Instantiates the datetime class and passes in the corresponding parameters, receiving a combination of the date and time instantiation parameters, where the date parameter is required and the other parameters have default values.

    1
    2
    
    >>> datetime(year=2021, month=4, day=29)
    datetime.datetime(2021, 4, 29, 0, 0)
    
  • Call the datetime.now() or datetime.utcnow() class method, the difference is that the instances have different corresponding time zones.

    1
    2
    3
    4
    
    >>> datetime.now()
    datetime.datetime(2021, 4, 29, 16, 4, 53, 648203)
    >>> datetime.utcnow()
    datetime.datetime(2021, 4, 29, 8, 5, 1, 671572)
    
  • Call the datetime.fromtimestamp(timestamp) or datetime.utcfromtimestamp(timestamp) class method and pass in the timestamp, the difference being that the instances have different corresponding time zones.

    1
    2
    3
    4
    5
    
    >>> import time
    >>> datetime.utcfromtimestamp(time.time())
    datetime.datetime(2021, 4, 29, 8, 6, 4, 798136)
    >>> datetime.fromtimestamp(time.time())
    datetime.datetime(2021, 4, 29, 16, 6, 26, 251251)
    
  • Create an instance from the iso string by calling the datetime.fromisoformat(time_string) class method.

    1
    2
    
    >>> datetime.fromisoformat('2021-04-29 16:09:32')
    datetime.datetime(2021, 4, 29, 16, 9, 32)
    
  • Creates a new datetime instance from a date instance and a time instance by calling the datetime.combine(date, time) class method.

    1
    2
    
    >>> datetime.combine(date.today(), time(16, 12))
    datetime.datetime(2021, 4, 29, 16, 12)
    
  • Parses the formatted string and creates a new instance by calling the datetime.strptime(date_string, format) class method.

Supported Operators

  • datetime supports equality comparisons with date, but the result must be False, except that only comparisons with another datetime object such as ==, , <, , > are supported.
  • Supports adding with timedelta, which results in datetime, adding and subtracting with timedelta, which still results in datetime, and subtracting with another datetime object, which results in timedelta.
  • Hashing is also supported.

Instance Methods

In addition to the strftime(), timetuple(), isoformat() and replace() methods inherited from date, the following methods are available.

  • timestamp(self) returns a POSIX timestamp in floating-point format.

    1
    2
    3
    
    >>> dt = datetime.now()
    >>> dt.timestamp()
    1619685580.762657
    
  • date(self) returns a date object representing the date part.

    1
    2
    
    >>> dt.date()
    datetime.date(2021, 4, 29)
    
  • time(self) returns a time object representing the time and minute part.

1
2
>>> dt.time()
datetime.time(16, 39, 40, 762657)

instance properties

Has all the properties of both the date and time instances.

timedelta

represents the difference between two datetime objects.

Instance construction method

  • Instantiates the timedelta class and passes in the corresponding parameters, receiving essentially the same parameters as the datetime class but without the year, both with a default value of 0.

    1
    2
    
    >>> timedelta(days=2)
    datetime.timedelta(days=2)
    
  • Perform subtraction of two datetimes.

    1
    2
    3
    4
    
    >>> dt1 = datetime.now()
    >>> dt2 = datetime.now()
    >>> dt2 -dt1
    datetime.timedelta(seconds=4, microseconds=476390)
    

Supported Operators

  • Only comparisons with another timedelta are supported for ==, , <, , >, etc.
  • The timedelta object supports addition and subtraction operations, and adding or subtracting datetime from timedelta still returns datetime.
  • timedelta also supports operators such as multiply and divide modulo divide.
  • Hashing is supported.
  • timedelta is signed and supports the abs() function, which returns the absolute interval between two datetimes.
1
2
3
4
5
6
7
8
9
>>> dt1 = datetime.now()
>>> dt2 = datetime.now()
>>> td = dt1 - dt2
>>> td
datetime.timedelta(days=-1, seconds=86395, microseconds=573188)
>>> td.total_seconds()
-4.426812
>>> abs(td)
datetime.timedelta(seconds=4, microseconds=426812)

Instance Method

  • total_seconds(self) Returns all seconds of the interval.

    1
    2
    3
    
    >>> d = timedelta(minutes=3, seconds=35)
    >>> d.total_seconds()
    215.0
    

Instance Properties

timedelta only keeps the time interval in a combination of days, seconds, microseconds, which can be obtained by the corresponding property.

1
2
3
4
5
6
7
8
>>> d1 = timedelta(minutes=3, seconds=35)
>>> d1
datetime.timedelta(days=0, seconds=215, microseconds=0)
>>> d2 = timedelta(days=1)
>>> d2
datetime.timedelta(days=1)
>>> d2.seconds
0

Summary comparison

Differences between the time and datetime modules

  • time module, get system timestamp, mainly used for timing or representing a point in time, can represent structured datetime by numeric meta-grandfather, but does not support further conversions or operations.
  • datetime module, constructs higher-order date, time, interval, etc. objects based on timestamps, supports rich conversion methods and operations.

Differences between different objects in the datetime module

  • date only represents dates. Supports adding and subtracting with date or timedelta.
  • time only represents the time and minute. It does not support adding or subtracting with time or timedelta, and the interval needs to be converted to a datetime object.
  • datetime is a time object that represents both date and time and minute. It has the behavior and properties of both date and time objects, from which separate date and time objects can be resolved.
  • timedelta represents the interval between two times. It is expressed only in days, seconds, and microseconds.

String formatting and parsing

String formatting and parsing.

  • time.struct_time, datetime.date, datetime.time, datetime.datetime, and other objects can be converted to strings of the specified format by the strftime() (string format) instance method or function.
  • Strings of a specific format can only be converted directly to time.struct_time, datetime.datetime objects by the strptime() (string parse) class method or function.

ISO format string formatting and parsing.

  • datetime.date, datetime.time, datetime.datetime objects can be converted to ISO 8601 format strings by the isoformat() instance method.
  • ISO 8601 format strings can be directly converted to datetime.date, datetime.time, datetime.datetime objects by the fromisoformat() class method.

chart

Summarize the above in a chronological chart.

python time & datetime