search
HomeBackend DevelopmentPython TutorialDetailed explanation of time module in Python
Detailed explanation of time module in PythonJun 10, 2023 am 11:17 AM
time processing (time)Module usage (module)python programming (python)

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)

Output:

当前时间戳: 1563431484.0177832

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)

Output:

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

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("程序执行结束。")

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)

Output:

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

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)

输出:

转换后的时间元组: 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)

在上述代码中,我们使用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)

输出:

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

在上述代码中,我们首先将两个时间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)

输出:

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

在上述代码中,我们首先将时间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)

输出:

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

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

Formatting characters Meaning
%a Abbreviation of day of the week
%A Full name of day of the week
%b Abbreviation of month
%B Full name of month
%c Local corresponding time Representation format
%d The day of the month

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
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
How to Use Python to Find the Zipf Distribution of a Text FileHow to Use Python to Find the Zipf Distribution of a Text FileMar 05, 2025 am 09:58 AM

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Image Filtering in PythonImage Filtering in PythonMar 03, 2025 am 09:44 AM

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

How to Work With PDF Documents Using PythonHow to Work With PDF Documents Using PythonMar 02, 2025 am 09:54 AM

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images. Fortunately, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me. Preparation The core lies in using external module PyPDF2. First, install it using pip: pip is P

How to Cache Using Redis in Django ApplicationsHow to Cache Using Redis in Django ApplicationsMar 02, 2025 am 10:10 AM

This tutorial demonstrates how to leverage Redis caching to boost the performance of Python applications, specifically within a Django framework. We'll cover Redis installation, Django configuration, and performance comparisons to highlight the bene

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Introduction to Parallel and Concurrent Programming in PythonIntroduction to Parallel and Concurrent Programming in PythonMar 03, 2025 am 10:32 AM

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

How to Implement Your Own Data Structure in PythonHow to Implement Your Own Data Structure in PythonMar 03, 2025 am 09:28 AM

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools