Table of Contents
struct_time is converted into a string and the string is converted into struct_time
Measuring the running time of a program
datetime
timedelta represents a period of time
将datetime转化为字符串形式及字符串转为datetime对象
Home Backend Development Python Tutorial Detailed introduction to Python's time and datetime modules

Detailed introduction to Python's time and datetime modules

Jul 20, 2017 pm 03:33 PM
datetime python time

There are three main formats for time expression in the time module:

a. timestamp, which means starting from 00:00:00 on January 1, 1970 Offset calculated in seconds

b. struct_time time tuple, a total of nine element groups.

c. format time format time. The formatted structure makes the time more readable. Includes custom formats and fixed formats.

time

The commonly used functions are time.time() and time.sleep().

import timeprint(time.time())
Copy after login
1499305554.3239055
Copy after login

The above floating point number is called the UNIX epoch timestamp, which is the number of seconds that have passed from 0:00 on January 1, 1970 to today. You can see that there are 6 decimal places at the end. Using the round function, you can round floating point numbers. As follows

# 默认四舍五入到整数位,即不保留小数print(round(time.time()))# 可指定参数保留的小数位数print(round(time.time(), 2))
Copy after login
1499305554
1499305554.49
Copy after login

time.sleep(sec) can make the current sleep, and fill in seconds (s) as the parameter.

print('good')
time.sleep(5.5)# 5.5秒后才打印这句print('yes')
Copy after login
good
yes
Copy after login

Using some other functions

# 返回UTC时间print(time.gmtime())# 返回本地时间,在中国就是UTC+8print(time.localtime())
Copy after login
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=6, tm_hour=1, tm_min=46, tm_sec=0, tm_wday=3, tm_yday=187, tm_isdst=0)
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=6, tm_hour=9, tm_min=46, tm_sec=0, tm_wday=3, tm_yday=187, tm_isdst=0)
Copy after login

You can find that this is a tuple type, and the time zone of China is UTC+8. It can be found that except tm_hour is different (their difference is exactly +8), the rest are the same.

The following function can return a formatted date and time, which looks more intuitive.

print(time.ctime())print(time.asctime())# 由于使用默认参数和上面的结果一样print(time.ctime(time.time()))print(time.asctime(time.localtime()))
Copy after login
Thu Jul  6 09:46:15 2017
Thu Jul  6 09:46:15 2017
Thu Jul  6 09:46:15 2017
Thu Jul  6 09:46:15 2017
Copy after login
  • ctime()You can pass in a timestamp. When no parameters are specified, the current one is used by default. Timestamp as parameter. That is, time.time()

  • gtime() can pass in a struct_time. When no parameters are specified, By default, the current time is used. That is, time.localtime()

struct_time is converted into a string and the string is converted into struct_time

  • strptime One parameter is the date in string form, and the second parameter is a custom date conversion format. The formats of these two parameters must correspond. For example, time.strptime('2017/7/6', '%Y-%m-%d')If one uses a slash and the other uses a dash, an error will be reported. This function returns a struct_time

  • The first parameter of strftime is the date format you want to convert it to, and the second parameter is a struct_time. This function converts the tuple form of struct_time into The format specified by the first parameter is the converted date string format.

%Y-%m-%d represents the year, month and day, which will be introduced in detail in the datetime module.

a = time.strptime('2017/7/6', '%Y/%m/%d')
b = time.strftime('%Y-%m-%d', time.localtime())print(a)print(b)
Copy after login
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=187, tm_isdst=-1)
2017-07-06
Copy after login

Measuring the running time of a program

Using timestamps can conveniently time the running time of a program

start_time = time.time()sum = 0for i in range(10000000):sum += 1end_time = time.time()print(end_time - start_time)
Copy after login
2.185124397277832
Copy after login

You can see that the loop calculation and addition is executed 10 million times, and that program took more than 2 seconds.

You can also use the time.clock() function

start = time.clock()print(start)  # 2.6773594453225194e-06time.sleep(2)
end = time.clock()print(end - start)  # 差值代表了睡眠2秒的时间。2.000246763295544time.sleep(3)print(time.clock())  # 5.00058991153112,返回的是从第一次调用到这次调用的时间间隔
Copy after login
4.4622657422041984e-07
2.0026006084745567
5.013243112269714
Copy after login

You can see clock when it is called for the first time Strangely, it returns the time the process is running. Any subsequent calls will be different from the value of the first call to clock. That is, the time elapsed from the first call to the current call to clock.
Like the above, set start above the part of the code you want to test, and set end at the end. You can also get the running time of the fragment code by subtracting it, and it is more accurate than time.time() .

datetime

datetime module is used to manage date and time, which has three sub-modules. They are time, date, datetime, so if you want to use datetime, you can use the following import method.

from datetime import datetime# 返回当前时间now = datetime.now()print(now.year, now.month, now.microsecond)# 可以自定义参数,返回格式化后的时间dt = datetime(2017, 10, 1, 23, 59, 59, 456123)print(dt)
Copy after login
2017 7 719609
2017-10-01 23:59:59.456123
Copy after login

datetime accepts 7 parameters, corresponding to year, month, day, hour, minute, second and microsecond. Saved in the year, month, day, hour, minute, second, microsecond attributes of datetime respectively.

The timestamp can be converted into datetime type. As follows, use the timestamp of the current time. Actually equivalent to datetime.now(). Of course, it is also possible to get the timestamp from datetime.

# 时间戳转datetimenow = datetime.fromtimestamp(time.time())print(now)
sometime = datetime(2017, 7, 5, 23, 59, 59)# datetime转时间戳print(sometime.timestamp())
Copy after login
2017-07-06 09:46:07.903769
1499270399.0
Copy after login

These datetime objects can use the ><= symbol to compare the sequence of two dates. Subtraction operations can also be performed to express the difference between two moments. For example,

dt1 = datetime(2017, 5, 31)
dt2 = datetime(2017, 4, 1)print(dt1 - dt2)print(dt1 > dt2)
Copy after login
60 days, 0:00:00
True
Copy after login

timedelta represents a period of time

Note that it does not represent a moment, but a period of time.

import datetime

delta = datetime.timedelta(weeks=2, days=7, hours=1, seconds=59,microseconds=234353)
delta1 = datetime.timedelta(days=5, hours=2)print(delta.seconds)  # 返回属性hours和seconds的和print(delta.total_seconds()) # 只是以秒来表示这段时间print(delta > delta1)print(delta + delta1)
Copy after login
3659
1818059.234353
True
26 days, 3:00:59.234353
Copy after login

timedelta的接受的参数有weeks、days、hours、minutes、seconds、microseconds,但是其属性却只有days、seconds、microseconds。并且除了像datetime一样支持大小比较、减法运算外,还可以进行加法运算,表示两个时间段的差值

将datetime转化为字符串形式及字符串转为datetime对象

time模块也有这两个函数(见上面的例子),使用上比较累类似。

  • strptime按照指定格式将字符串形式的日期转换成datetime对象并返回。

  • strftime将一个datetime对象(比如now)根据指定的格式转换成字符串并返回。

from datetime import datetime

a = datetime.strptime(&#39;2017/7/6&#39;, &#39;%Y/%m/%d&#39;)
b = datetime.now().strftime(&#39;%Y-%m-%d&#39;)print(a)print(b)
Copy after login
2017-07-06 00:00:00
2017-07-06
Copy after login

关于日期时间的格式,看下表。

格式指令 含义
%Y 带世纪的四位年份,如2017
%y 后两位年份,如17表示2017
%m 月份,从01到12
%B 完整的月份,如November
%b 月份的简写,如Nov
%d 一个月中的第几天,如从01到31(如果有的话)
%j 一年中的第几天
%w 一周中的第几天
%A 完整的周几,如Monday
%a 简写的周几,如Mon
%H 24小时制的小时00-23
%h 12小时制的小时01-12
%M 分,00-59
%S 秒,00-59
%p AM或者PM

The above is the detailed content of Detailed introduction to Python's time and datetime modules. 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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Can vs code run python Can vs code run python Apr 15, 2025 pm 08:21 PM

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.

See all articles