1. Random Selection
Generate random numbers in Python using the random module.
1. Randomly select elements from the sequence, using Random.choice ()
Import random>>> values = [1, 2, 3, 4, 5, 6]>>> random.choice (values)3>> > Random.choice (values)3>>> Random.choice (values)1>>> Random.choice ( Values)1>>> Random.choice (values)4
2. Remove the specified number of elements, using random.sample ()
>>> Random.sample (values, 2) [1, 4]>>> random.sample (values, 2) [3, 5 ]>>> random.sample (values, 3) [5, 3, 2]>>> random.sample (values, 3) [ 1, 3, 2]
3. Sequence of scrambled sequences, can be used to shuffle, use Random.shuffle ()
>>> Random.shuffle (values)>>> values[2, 4, 5, 3, 6, 1]>>> Random.shuffle (values)>>> values[2, 6, 5, 4, 3, 1]
4. Generate random integers, using random.randint ()
>>> Random.randint (1, ten)3>>> random.randint (1, ten)10>>> Random.randint (1, ten)5
5. Generate floating-point numbers between 0 and 1 using random.random ()
>>> random.random ()0.31720220264500265>>> random.random ()0.8230452349376671 >>> random.random ()0.09307172325744872
6. Generate random bits of integers, using random.getrandbits ()
>>> random.getrandbits (859899606181938256764615251875627706548045135119258688489931>) >> random.getrandbits (582401031226834278134883678914218487507678688169321631685078)
2. Conversion of Time
The datetime module is used in 1.python to convert the time.
from Import Timedelta>>> a = Timedelta (days = 2, hours = 6)>>> b = timedelta (hours = 4.5) >>> C = A + b>>> c.days2>>> c.seconds37800>>> C.seconds/360010.5>>> c.total_seconds ()/360058.5
Represents a specific date and time.
from Import datetime>>> a = DateTime (9, 8)print(A + timedelta (days=2)) 2017-09-10 00:00:00>>> B = DateTime (9, a)>>> d = B- a>>> d.days
14>>> now = datetime.today ()print(now)print(now + timedelta ( minutes=10))2017-09-08 20:19:56.904169
2. Using the Dateutil module, you can handle the number of days in different months. DateTime cannot process months.
>>> fromDateutil.relativedeltaImportRelativedelta>>> A = DateTime (2017, 9, 8)>>> A + relativedelta (Months=1) Datetime.datetime (2017, 10, 8, 0, 0)>>> A + relativedelta (months=4) Datetime.datetime (2018, 1, 8, 0, 0)
>>> B = DateTime (2017, 11, 11)>>> d = B-a>>>Ddatetime.timedelta (64)
>>> d =Relativedelta (b, a)>>>Drelativedelta (Months=+2, Days=+3)>>>d.months2>>>d.days3
3. Convert string to time, use Datetime.strptime (), convert time to string using Datetime.strftime ()
>>> fromDatetimeImportdatetime>>> Text ='2017-9-8'>>> y = datetime.strptime (text,'%y-%m-%d')>>> z =DateTime.Now ()>>> diff = z-y>>>Diffdatetime.timedelta (0,73494, 826144)>>>Ydatetime.datetime (2017, 9, 8, 0, 0)>>>Zdatetime.datetime (2017, 9, 8, 20, 24, 54, 826144)>>> nice_z = Datetime.strftime (Z,'%A%B%d%Y')>>>nice_z'Friday September'
Fluent Python and Cookbook Learning Notes (v)