python language time library and datetime library basic use details

  • 2021-08-31 08:34:50
  • OfStack

Today is the third day of writing a blog while reviewing. I am a sophomore this year, and we specialize in this course. Because I like it, I study it more seriously. I thought no one looked at it. After reading the background page views, I created it more seriously. This blog took me two and a half hours to write in combination with what I learned, thought and thought. The purpose is to facilitate Xiaobai who likes Python to learn, and it is also a kind of self-spur!

The python language uses the built-in time and datetime libraries to process dates and times

Explanation of related terms

UTC time Coordinated Universal Time, Universal Coordinated Time, also known as Greenwich Astronomical Time and Universal Standard Time. Corresponding to UTC time is local time in each time zone, and the time in East N is N hours earlier than that in UTC, so UTC time + N hours is the local time in East N; However, the time in west N area is N hours later than that in UTC, that is, ES29time-N hours is the local time in west N area; China is in East Area 8, so it is 8 hours earlier than UTC, which can be expressed as UTC+8. epoch time represents the starting point of time; It is a specific time, and the value of this time point is different on different platforms. For Unix, epoch time is 1970-01-01 00: 00:00 UTC. timestamp (timestamp) is also referred to as Unix time or POSIX time; It is a time representation that represents the number of milliseconds that have elapsed since 0:00:0 GMT on January 1, 1970, and its value is float type. However, some programming language related methods return seconds (Python is the case), which depends on the documentation of the method. It should be noted that the timestamp is a difference, and its value has nothing to do with the time zone.

There are three ways to call the library:

Take the time library as an example, calling other libraries is similar


from time import * (* Representative time Contains all the time processing functions, which can also be defined and used directly when calling functions, such as: clock())
import time  ( Call function mode , For example: time.clock())
import time as t ( Customize the name of the library, which is convenient to call, such as: t.clock())

The three main types of functions of the time library:

Take the third library call method above as an example

1. Time acquisition: t. time (); t. ctime (); t. gmtime () # Each kind of acquisition time is not 1, and it can be used according to requirements
2. Program timing: t. clock (); t. perf_counter () # Usage 1 Sample
3. Time formatting: t. strftime (format, t); t. strptime (string, format)
# format denotes the format to be defined, t denotes the fetched time, and string denotes the string type time
String formatting:% y two-digit year representation (00-99)
% Y 4-digit year representation (000-9999)
% m month (01-12)
1 day in% d month (0-31)
% H 24 Hours (0-23)
% I 12 Hours (01-12)
% M minutes (00=59)
% S seconds (00-59)
4. Program hibernation: t. sleep ()


# Use example 
import time as t
t0=t.gmtime()
print(t0)
t1="2020-12-23 19:23:20"
t2 = t.strptime(t1,"%Y-%m-%d %H:%M:%S")
t3 = t.strftime("%y/%m/%d %H:%M:%S")
print(t2)
print(t3)

Print results:
C:\ Users\ 86185\ PycharmProjects\ untitled\ venv\ python C:/Users/86185/PycharmProjects/untitled/Python Review/hk. py
time.struct_time(tm_year=2020, tm_mon=12, tm_mday=23, tm_hour=12, tm_min=22, tm_sec=39, tm_wday=2, tm_yday=358, tm_isdst=0)
time.struct_time(tm_year=2020, tm_mon=12, tm_mday=23, tm_hour=19, tm_min=23, tm_sec=20, tm_wday=2, tm_yday=358, tm_isdst=-1)
20/12/23 20:22:39

Process finished with exit code 0

time module is mainly used for time access and conversion, and this module provides various time-related functions.

方法/属性 描述
time.altzone 返回与utc时间的时间差,以秒为单位(西区该值为正,东区该值为负)。其表示的是本地DST 时区的偏移量,只有daylight非0时才使用。
time.clock() 返回当前进程所消耗的处理器运行时间秒数(不包括sleep时间),值为小数;该方法Python3.3改成了time.process_time()
time.asctime([t]) 将1个tuple或struct_time形式的时间(可以通过gmtime()和localtime()方法获取)转换为1个24个字符的时间字符串,格式为: "Fri Aug 19 11:14:16 2016"。如果参数t未提供,则取localtime()的返回值作为参数。
time.ctime([secs]) 功能同上,将1个秒数时间戳表示的时间转换为1个表示当前本地时间的字符串。如果参数secs没有提供或值为None,则取time()方法的返回值作为默认值。ctime(secs)等价于asctime(localtime(secs))
time.time() 返回时间戳(自1970-1-1 0:00:00 至今所经历的秒数)
time.localtime([secs]) 返回以指定时间戳对应的本地时间的 struct_time对象(可以通过下标,也可以通过 .属性名 的方式来引用内部属性)格式
time.localtime(time.time() + n*3600) 返回n个小时后本地时间的 struct_time对象格式(可以用来实现类似crontab的功能)
time.gmtime([secs]) 返回指定时间戳对应的utc时间的 struct_time对象格式(与当前本地时间差8个小时)
time.gmtime(time.time() + n*3600) 返回n个小时后utc时间的 struct_time对象(可以通过 .属性名 的方式来引用内部属性)格式
time.strptime(time_str, time_format_str) 将时间字符串转换为struct_time时间对象,如:time.strptime('2017-01-13 17:07', '%Y-%m-%d %H:%M')
time.mktime(struct_time_instance) 将struct_time对象实例转换成时间戳
time.strftime(time_format_str[, struct_time_instance]) 将struct_time对象实例转换成字符串,如果struct_time_instance不指定则取当前本地时间对应的time_struct对象

The four main types of functions in the datetime library are:

The datetime library is encapsulated based on the time library; Taking import datetime as dt as the calling mode of datetime library

1. date: Represents the date object # dt. date
2. time; Represents the time object # dt. time; date and time functions are not used in general, and datetime functions include their functions
3. datetime: Represents the date-time object # dt. datetime. now () represents getting the current time; dt. strftime (format) # Formatted output according to format
4. timedelta: Mainly used to define the calculation time span # t=dt. timedelat (hours=10) means that the defined time span is 10 hours

Classification with separator '''is shown as follows:


import datetime as dt
now = dt.datetime.now() #  Gets the current datetime
print(now)
 Output: 2019-05-07 16:28:07.198690
'''
d = dt.date(2020, 12, 23)
print(d)
print('year:', d.year)
print('month:', d.month)
print('day:', d.day)
 Output: 
2020-12-23
year: 2020
month: 12
day: 23
'''
'''
date1=dt.date(2020,12,23)
timedel=dt.timedelta(days=4)# Indicates that the time span is 4 Days 
print('4 The date of the day after is: ', date1+timedel)
 Output: 4 The date of the day after is: 2020-12-27
'''

Finally, it is accompanied by a small program: analysis of text progress bar printing program


import time
scale = 100 # This can be set at will, depending on the requirements 
print(" Start of execution ".center(scale//2,'-'))# .center(a,'b') Function is the center character, and this program centers the "start of execution" character as scale//2 (See requirements customization) ,b Is a filler 
starttime = time.clock() #time Library built-in function, the first 1 The second use is to start timing 
for i in range(scale+1):
  a = '*' * i  # Will '*' Character following i Increase with the increase of 
  b = '.' * (scale - i) # Will '.' Characters follow ' *' Increase and decrease, the total number of two characters is scale Initial value quantity of 
  c = (i/scale) * 100 # Find a percentage 
  t = time.clock()-starttime # Calculate the time, the first 2 Secondary call time.clock The function indicates the end of timing 
  print("\r{:^3.0f}%[{}->{}]{:.2}s".format(c,a,b,t),end="")# Character formatting, looking at the needs, playing by yourself is how to look good and format 
  time.sleep(0.05) #time.sleep() Function means to let the program sleep, and the parameters in it are the sleep time defined at will according to the requirements 
print("\n"+" End of execution ".center(scale//2,'-'))# Ibid. ;"\n Indicates line break printing " ; "+" Connector with connection function 

The datetime class of the datetime module will be explained in detail below, and time.struct_time will be briefly described here.

time.struct_time contains the following properties:

下标/索引 属性名称 描述
0 tm_year 年份,如 2017
1 tm_mon 月份,取值范围为[1, 12]
2 tm_mday 1个月中的第几天,取值范围为[1-31]
3 tm_hour 小时, 取值范围为[0-23]
4 tm_min 分钟,取值范围为[0, 59]
5 tm_sec 秒,取值范围为[0, 61]
6 tm_wday 1个星期中的第几天,取值范围为[0-6],0表示星期1
7 tm_yday 1年中的第几天,取值范围为[1, 366]
8 tm_isdst 是否为夏令时,可取值为:0 , 1 或 -1

There are two ways to get attribute values:

It can be regarded as a special ordered immutable sequence to obtain the values of each element through subscript/index, such as t [0] You can also get the value of each element by. attribute name, such as t.tm_year.

It should be noted that the properties of the struct_time instance are read-only and cannot be modified.


Related articles: