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 sinceepochas 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_timeand timestamp-
time.gmtime([secs])converts the given number of seconds to a UTC time zonestruct_timeobject, 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_timeobject in the local time zone, or uses the return value fromtime.time()if no seconds are provided. -
time.mktime(t)converts astruct_timeobject to seconds, which will be treated as a local time zone, with exactly the opposite effect oftime.localtime([secs]).
-
-
Convert between
struct_timeand a string-
time.strftime(format[, t])formats astruct_timeobject to a string in the specifiedformatencoding, and the default value oftis the return value oftime.localtime(). -
time.strptime(string[, format]parses a string into astruct_timeobject with the specifiedformatencoding, the default value offormatis"%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
dateclass 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 sinceepochobtained via thetimemodule (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 anotherdateobject. - Supports adding and subtracting from a
timedeltaobject, the result is still adateobject. - Supports subtracting from another
dateobject to get atimedeltaobject. - Hashing is supported.
Instance Methods
-
strftime(self, fmt)Returns a string representation of the currentdateobject in the specifiedfmtformatting code. -
isoformat(self)returns theisostring representation of the currentdateobject. -
timetuple(self)converts the currentdateobject to thetimemodule’sstruct_timeobject 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 currentdateobject after replacing one of its attributes. -
weekday(self)returns the week to which the currentdateobject belongs, starting from 0.
Instance Properties
yearmonthday
time
Indicates the time (hour, minute, and second) type.
Instance construction method
time does not support constructing instances by timestamp.
-
Instantiate the
timeclass 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
isostring by calling thefromisoformat(cls, time_string)class method.
Supported Operators
- Supports comparison operations such as
==,≤,<,≥,>with anothertimeobject. - 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 currenttimeobject in the specifiedfmtformatting code. -
isoformat(self)returns theisostring representation of the currenttimeobject. -
replace(self,hour=None,minute=None,second=None,microsecond=None, tzinfo=True, *,fold=None)Returns a copy of the currenttimeobject after replacing one of its attributes.
Instance Properties
hourminutesecond- 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
datetimeclass and passes in the corresponding parameters, receiving a combination of thedateandtimeinstantiation 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
isostring by calling thedatetime.fromisoformat(time_string)class method. -
Creates a new
datetimeinstance from adateinstance and atimeinstance 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
datetimesupports equality comparisons withdate, but the result must beFalse, except that only comparisons with anotherdatetimeobject such as==,≤,<,≥,>are supported.- Supports adding with
timedelta, which results indatetime, adding and subtracting withtimedelta, which still results indatetime, and subtracting with anotherdatetimeobject, 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 adateobject representing the date part. -
time(self)returns atimeobject 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
timedeltaclass and passes in the corresponding parameters, receiving essentially the same parameters as thedatetimeclass but without the year, both with a default value of 0. -
Perform subtraction of two
datetimes.
Supported Operators
- Only comparisons with another
timedeltaare supported for==,≤,<,≥,>, etc. - The
timedeltaobject supports addition and subtraction operations, and adding or subtractingdatetimefromtimedeltastill returnsdatetime. timedeltaalso supports operators such as multiply and divide modulo divide.- Hashing is supported.
timedeltais 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
timemodule, 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.datetimemodule, 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
dateonly represents dates. Supports adding and subtracting withdateortimedelta.timeonly represents the time and minute. It does not support adding or subtracting withtimeortimedelta, and the interval needs to be converted to adatetimeobject.datetimeis a time object that represents both date and time and minute. It has the behavior and properties of bothdateandtimeobjects, from which separatedateandtimeobjects can be resolved.timedeltarepresents 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.datetimeobjects by thestrptime()(string parse) class method or function.
ISO format string formatting and parsing.
datetime.date,datetime.time,datetime.datetimeobjects 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.datetimeobjects by thefromisoformat()class method.
chart
Summarize the above in a chronological chart.