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.
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.
Common uses and functions
-
Timing
-
time.time()
returns the number of seconds that have elapsed sinceepoch
as a floating point number. Common usage is to derive the program execution time by counting the interval between two calls. -
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 replacetime.time()
above when calculating execution times.
-
-
Convert between
struct_time
and timestamp-
time.gmtime([secs])
converts the given number of seconds to a UTC time zonestruct_time
object, or uses the return value obtained fromtime.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 astruct_time
object in the local time zone, or uses the return value fromtime.time()
if no seconds are provided. -
time.mktime(t)
converts astruct_time
object to seconds, which will be treated as a local time zone, with exactly the opposite effect oftime.localtime([secs])
.
-
-
Convert between
struct_time
and a string-
time.strftime(format[, t])
formats astruct_time
object to a string in the specifiedformat
encoding, and the default value oft
is the return value oftime.localtime()
. -
time.strptime(string[, format]
parses a string into astruct_time
object with the specifiedformat
encoding, the default value offormat
is"%a %b %d %H:%M:%S %Y"
.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. -
The
date.fromtimestamp(timestamp)
class method is called with the number of seconds sinceepoch
obtained via thetime
module (i.e., the timestamp). -
Calling the
date.today()
class method, which is essentially calling thedate.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.
Supported Operators
- Supports comparison operations such as
==
,≤
,<
,≥
,>
with anotherdate
object. - Supports adding and subtracting from a
timedelta
object, the result is still adate
object. - Supports subtracting from another
date
object to get atimedelta
object. - Hashing is supported.
Instance Methods
-
strftime(self, fmt)
Returns a string representation of the currentdate
object in the specifiedfmt
formatting code. -
isoformat(self)
returns theiso
string representation of the currentdate
object. -
timetuple(self)
converts the currentdate
object to thetime
module’sstruct_time
object and returns it, with attributes such as hours, minutes and seconds filled in using the default values. -
replace(self, year=None, month=None, day=None)
returns a copy of the currentdate
object after replacing one of its attributes. -
weekday(self)
returns the week to which the currentdate
object belongs, starting from 0.
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. -
Create an instance from the
iso
string by calling thefromisoformat(cls, time_string)
class method.
Supported Operators
- Supports comparison operations such as
==
,≤
,<
,≥
,>
with anothertime
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:
Instance Methods
-
strftime(self, fmt)
Returns a string representation of the currenttime
object in the specifiedfmt
formatting code. -
isoformat(self)
returns theiso
string representation of the currenttime
object. -
replace(self,hour=None,minute=None,second=None,microsecond=None, tzinfo=True, *,fold=None)
Returns a copy of the currenttime
object after replacing one of its attributes.
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 thedate
andtime
instantiation parameters, where the date parameter is required and the other parameters have default values. -
Call the
datetime.now()
ordatetime.utcnow()
class method, the difference is that the instances have different corresponding time zones. -
Call the
datetime.fromtimestamp(timestamp)
ordatetime.utcfromtimestamp(timestamp)
class method and pass in the timestamp, the difference being that the instances have different corresponding time zones. -
Create an instance from the
iso
string by calling thedatetime.fromisoformat(time_string)
class method. -
Creates a new
datetime
instance from adate
instance and atime
instance by calling thedatetime.combine(date, time)
class method. -
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 withdate
, but the result must beFalse
, except that only comparisons with anotherdatetime
object such as==
,≤
,<
,≥
,>
are supported.- Supports adding with
timedelta
, which results indatetime
, adding and subtracting withtimedelta
, which still results indatetime
, and subtracting with anotherdatetime
object, which results intimedelta
. - 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. -
date(self)
returns adate
object representing the date part. -
time(self)
returns atime
object representing the time and minute part.
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 thedatetime
class but without the year, both with a default value of 0. -
Perform subtraction of two
datetime
s.
Supported Operators
- Only comparisons with another
timedelta
are supported for==
,≤
,<
,≥
,>
, etc. - The
timedelta
object supports addition and subtraction operations, and adding or subtractingdatetime
fromtimedelta
still returnsdatetime
. timedelta
also supports operators such as multiply and divide modulo divide.- Hashing is supported.
timedelta
is signed and supports theabs()
function, which returns the absolute interval between twodatetimes
.
Instance Method
-
total_seconds(self)
Returns all seconds of the interval.
Instance Properties
timedelta
only keeps the time interval in a combination of days
, seconds
, microseconds
, which can be obtained by the corresponding property.
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 withdate
ortimedelta
.time
only represents the time and minute. It does not support adding or subtracting withtime
ortimedelta
, and the interval needs to be converted to adatetime
object.datetime
is a time object that represents both date and time and minute. It has the behavior and properties of bothdate
andtime
objects, from which separatedate
andtime
objects can be resolved.timedelta
represents the interval between two times. It is expressed only indays
,seconds
, andmicroseconds
.
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 thestrftime()
(string format) instance method or function.- Strings of a specific format can only be converted directly to
time.struct_time
,datetime.datetime
objects by thestrptime()
(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 theisoformat()
instance method.- ISO 8601 format strings can be directly converted to
datetime.date
,datetime.time
,datetime.datetime
objects by thefromisoformat()
class method.
chart
Summarize the above in a chronological chart.