Python Route (13th) Time module, random module, string module, verification code exercise

Source: Internet
Author: User
Tags month name printable characters shuffle

Python Road (13th) "Day21" Time module, random module, string module, verification code practiceOne, Time modulethree types of time representation

In Python, there are usually several ways to represent time:

    • Timestamp (timestamp): Typically, a timestamp represents an offset that is calculated in seconds, starting January 1, 1970 00:00:00. (from 1970 to now this moment total number of seconds) we run "type (Time.time ())" and return the float type. such as Time.time () =1525688497.608947

    • Formatted time string (string time) such as "2018-05-06"

    • Tuple (Struct_time) (structured time): Struct_time A total of 9 elements in total nine elements: (year, month, day, hour, minute, second, week of the year, Day of the year, summer Time)

    • ?

1, Time.time ():

Returns the timestamp of the current time

  Import time  ti = time.time ()  print (TI)


Output results



2, Time.localtime ([secs])

Converts a timestamp to the struct_time of the current time zone, which is the time array format. The secs parameter is not provided, whichever is the current time.


  Import time  #没有参数  print (Time.localtime ())  #有参数  print (Time.localtime (1480000000))


Output results

  Time.struct_time (tm_year=2018, tm_mon=5, tm_mday=7, tm_hour=18, tm_min=46, tm_sec=25, tm_wday=0, tm_yday=127, TM_ISDST =0)  time.struct_time (tm_year=2016, tm_mon=11, tm_mday=24, tm_hour=23, tm_min=6, tm_sec=40, tm_wday=3, tm_yday=329 , tm_isdst=0)


Example 2

  Import Time  ?  T=time.localtime ()  print (t.tm_year)  #取结构化时间中单独的数值  Print (T.tm_mon)  print (T.tm_mday)


Output results

  2018  5  6


Structured time elements represent meaning

   Tm_year    #年 1970-2018  ?   Tm_mon     #月 1-12  ?   Tm_mday    #日 1-31  ?   Tm_hour    #时 0-23  ?   Tm_min     #分 0-59  ?   Tm_sec     #秒 0-59  ?   Tm_wday    #一周中得第几天 0-6  , Monday is 0, Sunday is 6  ?   Tm_yday    #一年中得第几天 0-365  ?   TM_ISDST   #是否是夏令时  0-1  ?


3, Gmtime ([secs])

Similar to the LocalTime () method, the Gmtime () method is a struct_time that converts a timestamp to the UTC time zone (0 o'clock Zone).

That is, the tuple value that returns the current GMT

4, Mktime (t)

Converts a struct_time to a timestamp.


  Import Time  print (Time.mktime (Time.localtime ()))


Output results



5, Asctime ([t])

A tuple or struct_time representing time is represented in this form: ' Sun June 20 23:21:05 1993 '.


  Import Time  print (Time.asctime (Time.localtime ()))


Output results

  Mon may  7 19:49:21 2018


6, CTime ([secs])

Converts a timestamp (a floating-point number in seconds) into the form of time.asctime (). If the parameter is not given or is

None, the default Time.time () will be the parameter.

Its function is equivalent to Time.asctime (time.localtime (secs)).

  Import Time  print (Time.ctime ())


Output results

  Mon may  7 20:17:12 2018


7, Strftime (format[, T])

Converts a tuple or struct_time that represents time, such as returned by Time.localtime () and Time.gmtime (), to a formatted time string. If T is not specified, the Time.localtime () is passed in. If any of the elements in the tuple are out of bounds, the ValueError error will be thrown.

python format symbols in time Date:
    %y Two-digit year representation (00-99)  ?  %Y Four-digit year representation (000-9999)  ?  %m month (01-12)  ?  One day in%d months (0-31)  ?  %H 24-hour hours (0-23) #注意是大写  ?  %I 12-hour hours (01-12)  ?  %M minutes (00=59) #注意是大写  ?  %s seconds (00-59) #注意是大写  ?  %a Local Simplified week name  ?  %A Local full week name  ?  %b a simplified local month name  ?  %B a local full month name  ?  The corresponding date representation and time representation of%c local  ?  %j Day of the Year (001-366)  ?  %p the equivalent of a local a.m. or p.m.  ?  %u weeks of the year (00-53) Sunday is the beginning of the week  ?  %w Week (0-6), Sunday for the beginning of the week  ?  %W Week of the Year (00-53) Monday is the beginning of the week  ?  %x Local corresponding date representation  ?  %x local corresponding time representation  ?  %Z the name of the current time zone  ?  Percent% of the number itself




  Import Time  ?  Print (Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ()))


Output results

  2018-05-07 20:33:32


8, Strptime (string[, format])

Converts a formatted time (string time) string to Struct_time. In fact it is inverse operation with strftime ().

  Import Time  ?  Print (Time.strptime ("2018/05/07 20:33:32", "%y/%m/%d%h:%m:%s")) #第一个参数这里的字符串分隔的字符 # can be defined by itself, the second parameter corresponds to the first parameter


Output results

  Time.struct_time (tm_year=2018, tm_mon=5, tm_mday=7, tm_hour=20, tm_min=33, tm_sec=32, tm_wday=0, tm_yday=127, TM_ISDST =-1)


You can also take a separate value here

  Import Time  ?  T=time.strptime ("2018/05/07 20:33:32", "%y/%m/%d%h:%m:%s")  print (t.tm_mday)  print (t.tm_year)


Output results



9. Sleep (secs)

The thread defers the specified time run, in seconds.

  Import Time  ?  S1 = "Hello"  s2 = "Nicholas"  print (S1)  Time.sleep (2)  print (s2)


Output results

    Hello  #程序延迟2秒后输出 "Nicholas"  


10. Clock () (Learn)

The Python Time Clock () function returns the current CPU times as a number of seconds in floating-point count. It is more useful than time.time () to measure the time spent on different programs.

It is important to note that the meanings are different on different systems. On a UNIX system, it returns "process time", which is a floating-point number (timestamp) in seconds. In Windows, the first call returns the actual time that the process is running. The second subsequent call is the elapsed time since the first call to the present. (actually based on QueryPerformanceCounter () on WIN32, which is more accurate than milliseconds)

Time different forms convert each other

second, random module

Modules that generate random values

1, random.random ()

Randomly produce decimals greater than 0 and less than 1

  Import random  v1 = random.random ()  


2, Random.uniform (A, b)

Returns a floating-point number between A and B. Typically a<b, that is, returns a floating-point number between A and B, or a floating-point number between B and a if a is greater than B. Both A and b here are likely to appear in the results.

  Import random  v1 = random.uniform (1.1,2.5) #这里的a, B is not necessarily an integer, is generally written as an integer  


3, Random.randint (A, b)

Returns an integer between Range[a,b], that is, an integer

  Import random  v1 = random.randint (1,3) #这里a, B must be an integer, and a, a, a, can appear in the result  


4, Random.randrange (Start, stop[, step])

Random.randrange (Start, stop[, step]) # Returns an integer between Range[start,stop), start\stop must be an integer, plus step, similar to Range (0,10,2).

  Import random  v1 = random.randrange (1,5,2)   


5, Random.choice (seq)

Randomly selects an element from a non-empty sequence seq (string is also a sequence). If seq is empty, the indexerror exception pops up.

  Import random  v1 = Random.choice ([1,5,2, "ni", {"K1": "v1"},["HI", 8]])  print (v1)


Output results

From the list [1,5,2, "ni", {"K1": "v1"},["HI", 8]] randomly returns an element

    Import Random  ?  Print (Random.choice ("Nicholas"))


Output results

Randomly returns a character of the string "Nicholas"

6, Random.sample (population, K)

Randomly select K non-repeating elements from a population sample or collection to form a new sequence

  Import random  v1 = random.sample ([1,5,2, "ni", {"K1": "v1"},["HI", 8]],3)  print (v1)


Output results

Randomly extract 3 non-repeating elements from a list to form a new list

7, Random.shuffle ()

Disturb the order of the list

  Import random  li = [1,5,2,3]  random.shuffle (LI)  print (LI)


Output: Output The list of 4 elements in a random order

three, String module (Learn)

The string method is shown in the previous blog post.

Here are some string constants

1, String.ascii_lowercase

Returns the lowercase letter ' abcdefghijklmnopqrstuvwxyz ' of the string

Import Stringprint (string.ascii_lowercase)


2, String.ascii_uppercase

Returns a string of uppercase letters ' ABCDEFGHIJKLMNOPQRSTUVWXYZ '

Import Stringprint (string.ascii_uppercase)


3, String.ascii_letters

Returns a string consisting of a lowercase a~z plus uppercase a~z, which is a string consisting of String.ascii_lowercase connection string.ascii_uppercase

Import Stringprint (string.ascii_letters)


4, String.digits

String of numbers 0 to 9: ' 0123456789 '

Import Stringprint (string.digits)


5, String.hexdigits

Returns the string ' 0123456789abcdefABCDEF ', which is a string of all hexadecimal characters (the English letter plus the case)

Import Stringprint (string.hexdigits)


6, String.letters

The results returned by String.letters in Python2 are the same as String.ascii_letters, and are canceled in Python3.

String.ascii_letters can be used in both Python2 and Python3.

7, String.lowercase

String.lowercase returns a string of lowercase ' abcdefghijklmnopqrstuvwxyz ' in Python2, consistent with String.ascii_lowercase and canceled in Python3

String.ascii_lowercase can be used in both Python2 and Python3.

8, String.uppercase

String.lowercase returns a string of uppercase letters ' ABCDEFGHIJKLMNOPQRSTUVWXYZ ' in Python2, consistent with String.ascii_uppercase, canceled in Python3

String.ascii_uppercase can be used in both Python2 and Python3.

9, String.octdigits

Returns a string consisting of all characters in octal

Import Stringprint (string.octdigits)


10, String.punctuation

Return all punctuation characters

Import Stringprint (string.punctuation)


Output results

!" #$%& ' () *+,-./:;<=>[email protected][\]^_ ' {|} ~


11, String.printable

Returns a string of all printable characters. Contains numbers, letters, punctuation, and spaces

Import Stringprint (string.printable)


Output results


Analysis: A string consisting of String.digits plus string.ascii_letters plus string.punctuation

Four, verification code practice

Generate four-bit digital verification code

1, Method one

  Import Random  li=[str (i) for I in Random.sample (range (0,10), 4)]  print ("". Join (LI))


2. Method Two

  Import random  li = [] for  I in range (4):      li.append (str (random.randint (0,9)))  print ("". Join (LI))


Generate four-bit verification codes with numbers and letters

1, Method one

  Import random  num_l = list (map (str,list (range))) #获取以0-9 String for the listing of elements  del_l = lists (range (91,97))  Chr_ L = [Chr (i) if I not in del_l else "for I in Range (65,123)] #获取大小写的a-Z list, remove the middle 6 special characters  num_l.extend (chr_l)  #将字母和 The numbers are grouped together  res_l = num_l  res_str = "". Join (res_l). Strip ("") #去掉空字符元素  print ("". Join (Random.sample (Res_ str,4)))


2. Method Two

Import Stringimport Randomres_str = ("%s%s")% (string.ascii_letters,string.digits) print ("". Join (Random.sample (Res_ str,4)))


Python Route (13th) Time module, random module, string module, verification code exercise

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.