python learning modules - Module (c)

5.6 time module

Common methods of time already knows: time.time () Gets the timestamp of the current time; time.sleep (num) thread postpone a specified time (seconds) and then continue down.

Time representation

Can be divided into: time stamp tuples (struct_time), the formatted time string

  • Timestamp --timestamp

Timestamp indicates that from the beginning of January 1970 00:00:00 1st, by second type is float

  • Formatted time string (Format String)
% Y represents two-digit year (00-99) % Y represents a four-digit year (000-9999)
% M (01-12) Within a% d day of the month (0-31)
% H 24 hours (0-23) manufactured by h % I 12 hours hour (01-12)
% M number of minutes (00 = 59) % S seconds (00-59)
% A week simplify local name % A full weekday name local
% B local simplify month name % B Full month name of the local
% C represents the corresponding date and time represent the local One day (001-366)% j years
% P local AM or PM equivalent character % U week number of the year (00-53) for the week beginning Sunday
% W week (0-6), Sunday is the start of week % W week number of the year (00-53) for the week beginning Monday
% X indicates the corresponding local date % X indicates the corresponding local time
Name% Z current time zone %%% Number itself
  • Tuple (struct_time)

struct_time tuple total of nine elements were nine elements :( year, month, day, hour, minute, second, the first few weeks of the year, day of the year, etc.)

Index (Index) Property (Attribute) Value (Values)
0 tm_year (years) For example, 2011
1 tm_mon (月) 1 - 12
2 tm_mday (Japan) 1 - 31
3 tm_hour (time) 0 - 23
4 tm_min (points) 0 - 59
5 tm_sec (s) 0 - 60
6 tm_wday(weekday) 0--6 (0 for Monday)
7 tm_yday (the first day of the year) 1 - 366
8 tm_isdst (whether it is daylight saving time) The default is 0

[Summary] timestamps are the computer can recognize time; who is able to read time string time; tuple is used to operate the time

import time  #导入时间模块

#时间戳
print(time.time())
# 1561729203.008572

#时间字符串
ft = time.strftime("%Y-%m-%d %H:%M:%S")  #格式化里的字符必须是ASCII里的元素,不能是汉字
print(ft)   #2019-06-28 21:42:24

#时间元组
tt = time.localtime()
print(tt)
# time.struct_time(tm_year=2019, tm_mon=6, tm_mday=28, tm_hour=21, tm_min=44, tm_sec=5, tm_wday=4, tm_yday=179, tm_isdst=0)
  • Conversion between several formats

#格式化时间---->结构化时间
ft1 = time.strftime("%Y-%m-%d %H:%M:%S")
st1 = time.strptime(ft1,"%Y-%m-%d %H:%M:%S")  #转成结构化时间,后边的格式必须要与格式化时间结构一致
print(st1)

#结构化时间--->时间戳
tt1 = time.mktime(st1)    #转换后,时间戳紧缺到小数点后一位
print(tt1)

#时间戳--->结构化时间
st2 = time.localtime(tt1)   #不传参,就是获取当前的结构化时间
print(st2)
st3 = time.gmtime(tt1)
print(st3)

#结构化时间--->格式化时间
ft2 = time.strftime("%Y-%m-%d %H:%M:%S",st3)   #strftime要把更改的时间放在第二个位置参数
print(ft2)
asctime 与 ctime
  • struct_time ----> format time format is fixed
st = time.localtime()  #获取当前结构化时间
print(st)
ft = time.asctime()   #获取当前格式化时间
print(ft)
ft1 = time.asctime(st)   #把结构化时间转换成固定格式的格式化时间,
print(ft1)
  • timestamp ----> format time format is fixed
tt = time.time()
ft = time.ctime()    #不传参,获取当前格式化时间
ft1 = time.ctime(tt)    #把时间戳时间转换成固定格式的格式化时间,
print(ft1)

[Practice] to calculate the time difference

sta_time = time.mktime(time.strptime('2017-12-23 08:30:00','%Y-%m-%d %H:%M:%S'))
end_time = time.mktime(time.strptime('2018-12-23 08:30:00','%Y-%m-%d %H:%M:%S'))
dif_time = end_time - sta_time
st = time.gmtime(dif_time)
print('过去了%d年%d月%d天%d小时%d分钟%d秒'%(st.tm_year-1970,st.tm_mon-1,
                                       st.tm_mday-1,st.tm_hour,
                                       st.tm_min,st.tm_sec))

5.7 datetime module

import datetime
now = datetime.datetime.now()
print(now)
print(datetime.datetime.now()+datetime.timedelta(weeks=4))  #4周后
print(datetime.datetime.now()+datetime.timedelta(weeks=-3)) #3周前
print(datetime.datetime.now() + datetime.timedelta(days=-2)) # 2天前
print(datetime.datetime.now() + datetime.timedelta(days=3)) # 三天后
print(datetime.datetime.now() + datetime.timedelta(hours=5)) # 5小时后
print(datetime.datetime.now() + datetime.timedelta(hours=-6)) # 6小时前
print(datetime.datetime.now() + datetime.timedelta(minutes=-10)) # 10分钟前
print(datetime.datetime.now() + datetime.timedelta(minutes=15)) # 15分钟后
print(datetime.datetime.now() + datetime.timedelta(seconds=-30)) # 30秒前
print(datetime.datetime.now() + datetime.timedelta(seconds=40)) # 40秒后

current_time = datetime.datetime.now()

print(current_time.replace(year=2008))  # 直接调整到2008年
print(current_time.replace(month=11))  # 直接调整到11月份
print(current_time.replace(year=1997,month=4,day=25))  # 1997-04-25 18:49:05.898601

# 将时间戳转化成时间
print(datetime.date.fromtimestamp(1232132131))  # 2009-01-17

5.8 random module

Generate random numbers

import random

# 随机生成小数
n1 = random.random()  #随机生成0-1范围内的小数

# 自定义范围的小数
n2 = random.uniform(1,4)  #可用于发红包

# 随机整数
n3 = random.randint(1,9)  #自定义范围内的整数, 1 <= n3 <= 9
n4 = random.randrange(1, 10, 2)   #[2,4,6,8]范围内的偶数,1 <= n4 < 10范围内的偶数

# 随机选择一个返回值
n5 = random.choice([1,'23',['a','c']])  #返回列表长得一个元素
n6 = random.sample((1,'23',['a','c']),2) #随机返回列表中的两个组合,原序列不变,返回值顺序不定
n7 = random.sample('12345',3)  #原序列不变,返回值顺序不定
# 这里的范围必须是有序类型的数据:Population must be a sequence or set,不能是字典和int类型

# 打乱列表顺序,仅限列表
li = [1,2,3,4,5,6]
random.shuffle(li)
print(li)

Exercise] [ generating check code 4

import random
def auth_num():
    s = ''
    for i in range(4):
        num = random.randint(0,9)
        alp = chr(random.randint(65,90))
        ALP = chr(random.randint(97,122))  #chr的作用Return a Unicode string of one character with ordinal i
        add = random.choice([num,alp,ALP])
        s += str(add)
    return s
code = auth_num()
print(code)

Guess you like

Origin www.cnblogs.com/jjzz1234/p/11106636.html