The Road to Python (Part 13) time module, random module, string module, verification code practice

 

The Road to Python (Part 13) [day21] time module, random module, string module, verification code practice

First, the time module

Three time representations

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

  • Timestamp: Generally speaking, a timestamp represents an offset in seconds from January 1, 1970 00:00:00. (How many seconds are there from 1970 to this moment) We run "type(time.time())" and it returns a float. Such as time.time()=1525688497.608947

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

  • Tuple (struct_time) (structured time): The struct_time tuple has a total of 9 elements. A total of nine elements: (year, month, day, hour, minute, second, the week of the year, the day of the year, summer time)

1、time.time():

Returns the timestamp of the current time

  import time
  ti = time.time ()
  print (you)

  

output result

  
  1525688497.608947

  

2、time.localtime( [secs] )

Convert a timestamp to a struct_time of the current time zone, that is, a time in time array format. If the secs parameter is not provided, the current time shall prevail.

example

  
  import time
  # no parameters
  print(time.localtime())
  # with parameters
  print(time.localtime(1480000000))

  

output result

  
  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) #Take individual values ​​in structured time
  print(t.tm_my)
  print(t.tm_mday)

  

output result

  
  2018
  5
  6

  

 

The meaning of each element of structured time

  
   tm_year #year 1970-2018
   tm_mon #Month 1-12
   tm_mday #Day 1-31
   tm_hour    #时 0-23
   tm_min #min 0-59
   tm_sec #sec 0-59
   tm_wday #Day of the week 0-6, Monday is 0, Sunday is 6
   tm_yday #The day of the year 0-365
   tm_isdst #Whether it is daylight saving time 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 (time zone 0).

That is, a tuple value that returns the current GMT

 

4、 mktime(t)

Convert a struct_time to a timestamp.

 

example

  
  import time
  print(time.mktime(time.localtime()))

  

output result

  
  1525693661.0

  

 

5、asctime([t])

Represent a tuple or struct_time representing a time of the form: 'Sun Jun 20 23:21:05 1993'.

example

  
  import time
  print(time.asctime(time.localtime()))

  

output result

  
  Mon May  7 19:49:21 2018

  

 

6、 ctime([secs])

Convert a timestamp (float in seconds) to the form of time.asctime(). If the parameter is not given or is

When None, it will default to time.time() as the parameter.

Its effect is equivalent to time.asctime(time.localtime(secs)).

  
  import time
  print(time.ctime())

  

output result

  
  Mon May  7 20:17:12 2018

  

 

7、 strftime(format[, t])

Converts a tuple representing a time or struct_time (as returned by time.localtime() and time.gmtime() ) to a formatted time string. If t is not specified, time.localtime() will be passed. If any element in the tuple is out of bounds, a ValueError will be thrown.

Time and date formatting symbols in python:

  
  %y Two-digit year representation (00-99)
  %Y Four-digit year representation (000-9999)
  %m month (01-12)
  %d day of the month (0-31)
  %H 24-hour hour (0-23) #Note that it is uppercase
  %I 12-hour clock (01-12)
  %M minutes (00=59) #Note that it is uppercase
  %S seconds (00-59) #Note that it is uppercase
  %a local abbreviated weekday name
  %A local full week name
  %b local abbreviated month name
  %B local full month name
  %c Local corresponding date representation and time representation
  Day of the year in %j (001-366)
  %p local AM or PM equivalent
  %U Week of the year (00-53) Sunday is the start of the week
  %w week (0-6), Sunday is the start of the week
  %W Week of the year (00-53) Monday is the start of the week
  %x local corresponding date representation
  %X local corresponding time representation
  %Z The name of the current time zone
  %%% sign itself

  


 

example

  
  import time
  print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))

  

output result

  
  2018-05-07 20:33:32

  

 

8、strptime(string[, format])

Converts a formatted time (string time) string to struct_time. In fact it is the inverse of strftime().

 

  
  import time
  print(time.strptime("2018/05/07 20:33:32","%Y/%m/%d %H:%M:%S")) #The first parameter here is separated by strings The character # can be defined by yourself, and the second parameter corresponds to the first parameter.

  

output result

  
  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 result

  
  7
  2018
 

  

9、sleep(secs)

The thread delays running for the specified time, in seconds.

  
  import time
  s1 = "Hello"
  s2 = "nicholas"
  print(s1)
  time.sleep(2)
  print(s2)

  

output result

  
  hello # program output "nicholas" after 2 seconds delay
  nicholas
 

  

10. clock() (understand)

The Python time clock() function returns the current CPU time in seconds as a floating point number. Used to measure the time-consuming of different programs, more useful than time.time().

It should be noted that this has different meanings on different systems. On UNIX systems, it returns the "process time", which is a floating point number (timestamp) in seconds. In WINDOWS, the first call returns the actual time the process is running. The call after the second time is the elapsed time since the first call. (Actually based on QueryPerformanceCounter() on WIN32, which is more accurate than milliseconds)

 

Converting different forms of time to each other

 

Second, the random module

A module that generates random numbers

 

1、random.random()

Randomly generate decimals between 0 and less than 1

  
  import random
  v1 = random.random()
  print(v1)
 

  

2、random.uniform(a, b)

Returns a float between a and b. Generally, a<b, that is, the floating-point number between a and b is returned. If a is greater than b, it is a floating-point number between b and a. Both a and b here may appear in the result.

  
  import random
  v1 = random.uniform(1.1,2.5) #here a, b are not necessarily integers, generally written as integers
  print(v1)
 

  

3、random.randint(a,b)

Returns an integer between range[a,b], which is an integer

  
  import random
  v1 = random.randint(1,3) #Here a, b must be integers, both a and b can appear in the result
  print(v1)
 

  

4 random.randrange (start, stop [, step])

random.randrange(start, stop[, step]) # Returns an integer between range[start,stop), start\stop must be an integer, and step can be added, similar to range(0,10,2).

  import random
  v1 = random.randrange (1,5,2)
  print(v1)
 

  

5、random.choice(seq)

Picks an element at random from the non-empty sequence seq (strings are also sequences). If seq is empty, an IndexError exception will pop up.

  
  import random
  v1 = random.choice([1,5,2,"ni",{"k1":"v1"},["hi",8]])
  print(v1)

  

output result

Returns a random element from the list [1,5,2,"ni",{"k1":"v1"},["hi",8]]

  
  import random
  print(random.choice("nicholas"))

  

output result

Randomly returns one character of the string "nicholas"

 

6、random.sample( population, k)

Randomly select k non-repeating elements from the population sample or set to form a new sequence

  
  import random
  v1 = random.sample([1,5,2,"ni",{"k1":"v1"},["hi",8]],3)
  print(v1)

  

output result

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

 

7、random.shuffle()

Shuffle the order of the list

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

  

Output result: output a list of these 4 elements in random order

 

Three, string module (understand)

See the previous blog post for string methods.

Here are some string constants

1、string.ascii_lowercase

Returns the string lowercase letters 'abcdefghijklmnopqrstuvwxyz'

import string
print(string.ascii_lowercase)

  



 

2、string.ascii_uppercase

Returns the uppercase letters of the string 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

import string
print(string.ascii_uppercase)

  



 

3、string.ascii_letters

Returns a string composed of lowercase a~z plus uppercase A~Z, that is, a string composed of string.ascii_lowercase concatenated with string.ascii_uppercase

import string
print(string.ascii_letters)

  



 

4、string.digits

String of numbers 0 to 9: '0123456789'

import string
print(string.digits)

  



5、string.hexdigits

Returns the string '0123456789abcdefABCDEF', which is a string composed of all hexadecimal characters (English letters plus uppercase and lowercase)

import string
print(string.hexdigits)

  



 

6、string.letters

The result returned by string.letters in python2 is the same as string.ascii_letters, which was canceled in python3,

string.ascii_letters can be used in both python2 and python3

 

7、string.lowercase

string.lowercase returns string lowercase letters 'abcdefghijklmnopqrstuvwxyz' in python2, consistent with string.ascii_lowercase, canceled in python3

string.ascii_lowercase can be used in both python2 and python3

 

8、string.uppercase

string.lowercase returns string 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 of all characters in octal

import string
print(string.octdigits)

  



 

10、string.punctuation

Returns all punctuation characters

import string
print(string.punctuation)

  



output result

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

  



 

 

11、string.printable

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

import string
print(string.printable)

  



output result

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

  



Analysis: that is, a string composed of string.digits plus string.ascii_letters plus string.punctuation

 

Four, verification code practice

Generate a four-digit verification code

1. Method 1

  
  import random
  li=[str(i) for i in random.sample(range(0,10),4)]
  print("".join(li))

  

2. Method 2

  
  import random
  li = []
  for i in range(4):
      li.append(str(random.randint(0,9)))
  print("".join(li))

  

 

Generate a four-digit verification code with numbers and letters

1. Method 1

  import random
  num_l = list(map(str,list(range(10)))) #Get a list with 0-9 strings as elements
  del_l = list(range(91,97))
  chr_l = [chr(i) if i not in del_l else ''for i in range(65,123)] #Get a list of upper and lower case az, remove the 6 special characters in the middle
  num_l.extend(chr_l) # Combine letters and numbers together
  res_l = num_l
  res_str = "".join(res_l).strip("") #Remove empty character elements
  print("".join(random.sample(res_str,4)))

  

2. Method 2

import string
import random
res_str = ("%s%s")%(string.ascii_letters,string.digits)
print("".join(random.sample(res_str,4)))

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325818099&siteId=291194637