Detailed explanation of time module in Python

王林
Release: 2023-06-10 11:17:13
Original
6112 people have browsed it

Detailed explanation of the time module in Python

In Python programming, we often need to process and operate time. The standard library in Python provides a time module for handling time-related operations. This article will introduce the time module in detail.

  1. Introduction to the time module

The time module is part of the Python standard library and provides some functions and classes for processing time. This module mainly includes the following aspects:

  1. Time acquisition: Get the current time and sleep waiting execution time.
  2. Time format conversion: Convert time to string or format string to time.
  3. Time calculation: Calculate the difference between two times.
  4. Time operation: perform operations such as addition, subtraction, comparison, and judgment on time.
  5. Time acquisition

The time module uses the time() function to obtain the timestamp of the current time. The following is a simple example:

import time

now = time.time()  
print("当前时间戳:", now)
Copy after login

Output:

当前时间戳: 1563431484.0177832
Copy after login

In order to facilitate us to view the time, the time module also provides an asctime() function to convert the timestamp to represent the local A string of times. The following is an example:

import time

now = time.time()
localtime = time.localtime(now)
asctime = time.asctime(localtime)

print("当前时间:", asctime)
Copy after login

Output:

当前时间: Mon Jul 18 14:04:44 2019
Copy after login

In addition, the sleep() function can cause the program to pause for a specified time (in seconds), allowing the program to wait for a period of time before executing. The following is an example of using the sleep() function:

import time

print("程序开始执行...")
time.sleep(5)
print("程序执行结束。")
Copy after login

When executing the above code, the program will pause for 5 seconds and then output "Program execution ends."

  1. Time format conversion

In Python programming, we often need to convert timestamps into human-readable time formats, or vice versa. The time module provides two main functions: strftime() and strptime(), which are used for time format conversion.

a. strftime()

The strftime() function is a function used to format time into a string. The following is an example:

import time

t = (2019, 7, 18, 14, 30, 0, 0, 0, 0)
localtime = time.mktime(t)
asctime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(localtime))

print("时间格式化字符串:", asctime)
Copy after login

Output:

时间格式化字符串: 2019-07-18 14:30:00
Copy after login

In the above code, we first convert the time t into the timestamp localtime, and then use the strftime() function to format the localtime as needed String form.

The parameters of the strftime() function include format strings and time tuples, where the format string is a template for converting time tuples into strings. Commonly used formatting characters are as follows:

##%H in 24 hours Express the number of hours in 12-hour format%IExpress the number of hours in 12-hour format%j The day of the year%mThe month represented by the number (01~12)%MMinutes%pAM or PM%S Seconds%UThe number of weeks in the year, Sunday is the beginning of the week%w Day of the week, 0 (Sunday) ~ 6 (Saturday) %WThe number of weeks in the year, Monday is The beginning of the week%xLocal corresponding date representation%XLocal corresponding time representation Format%yRemove the century year representation (00~99)%YComplete year representation (0000~9999)%zThe number of hours difference from UTC time% ZThe name of the time zone%%The character "%" itself

b. strptime()

strptime()函数则是将字符串转换为时间类型。以下是一个示例:

import time

str_time = "2019-07-18 14:30:00"
struct_time = time.strptime(str_time, "%Y-%m-%d %H:%M:%S")

print("转换后的时间元组:", struct_time)
Copy after login

输出:

转换后的时间元组: time.struct_time(tm_year=2019, tm_mon=7, tm_mday=18, tm_hour=14, tm_min=30, tm_sec=0, tm_wday=3, tm_yday=199, tm_isdst=-1)
Copy after login

在上述代码中,我们使用strptime()函数将格式为"%Y-%m-%d %H:%M:%S"的字符串str_time转换为时间元组。

  1. 时间计算

在Python编程中,我们也经常需要进行时间的计算,如计算两个时间之间的差值、或将一个时间加上或减去一段时间后得到一个新的时间。time模块中提供了很多函数来实现这些计算操作。

a. 时间差值计算

计算两个时间之间的差值可以使用time模块中的mktime()函数,该函数将时间元组转换为时间戳,我们可以通过计算两个时间的时间戳之差来得到它们之间的时间差。以下是一个示例:

import time

t1 = (2019, 7, 18, 14, 30, 0, 0, 0, 0)
t2 = (2019, 7, 19, 14, 30, 0, 0, 0, 0)

t1_stamp = time.mktime(t1)
t2_stamp = time.mktime(t2)

diff_secs = int(t2_stamp - t1_stamp)

print("两个时间之间相差的秒数:", diff_secs)
Copy after login

输出:

两个时间之间相差的秒数: 86400
Copy after login

在上述代码中,我们首先将两个时间t1、t2转换为时间戳t1_stamp、t2_stamp,接着计算两个时间戳之差得到时间差值(单位为秒)。

b. 时间加减计算

时间加减计算可以使用time模块中的mktime()函数和localtime()函数。我们可以将一个时间元组转换为时间戳,然后加上一段时间的秒数,再将结果转换为时间元组即可得到一个新的时间。以下是一个示例:

import time

t1 = (2019, 7, 18, 14, 30, 0, 0, 0, 0)
t1_stamp = time.mktime(t1)

days = 1
hours = 3
minutes = 30
seconds = 0

add_secs = days * 86400 + hours * 3600 + minutes * 60 + seconds

new_stamp = t1_stamp + add_secs

new_time = time.localtime(new_stamp)
new_strftime = time.strftime("%Y-%m-%d %H:%M:%S", new_time)

print("加上一段时间后的新时间:", new_strftime)
Copy after login

输出:

加上一段时间后的新时间: 2019-07-19 18:00:00
Copy after login

在上述代码中,我们首先将时间t1转换为时间戳t1_stamp,然后定义了要加的时间间隔,接着将时间间隔的总秒数计算出来,将其加上t1_stamp得到新的时间戳new_stamp,最后使用localtime()函数和strftime()函数将新的时间转换为字符串表示。

  1. 时间操作

time模块中定义了很多函数用于对时间进行各种操作。

a. 时间比较

time模块中的函数cmp()、min()和max()可以用来比较时间的大小。

b. 时间运算

time模块中的函数add()、sub()可以用来对时间进行加减运算。

c. 时间格式化

time模块中还提供了一个函数asctime(),用于将时间元组转换为表示当地时间的字符串。

以下是一个示例:

import time

t = (2019, 7, 18, 14, 30, 0, 0, 0, 0)

asctime = time.asctime(t)

print("时间格式化字符串:", asctime)
Copy after login

输出:

时间格式化字符串: Thu Jul 18 14:30:00 2019
Copy after login

以上是time模块的基本使用方式和一些常用函数的介绍。通过学习并掌握time模块的使用方法,我们可以更加方便地进行Python编程中的时间操作与计算。

The above is the detailed content of Detailed explanation of time module in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!
Formatting charactersMeaning
%aAbbreviation of day of the week
%AFull name of day of the week
%b Abbreviation of month
%BFull name of month
%cLocal corresponding time Representation format
%dThe day of the month