Detailed introduction to Python's time and datetime modules

零下一度
Release: 2017-07-20 15:33:15
Original
2518 people have browsed it

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!

Related labels:
source:php.cn
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template