0%

python-第六天学习

python3基础学习

时间库练习

假设你获取了用户输入的日期和时间如 2015-1-21 9:01:30,以及一个时区信息如UTC+5:00,均是 str,请编写一个函数将其转换为 timestamp:

1
2
3
4
5
6
7
8
9
10
11
12
13
# -*- coding:utf-8 -*-
import re
from datetime import datetime, timezone, timedelta
def to_timestamp(dt_str, tz_str):
----
pass
----
# 测试:
t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00')
assert t1 == 1433121030.0, t1
t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00')
assert t2 == 1433121030.0, t2
print('Pass')

贴上我的代码,不难,不过我写的有点复杂了感觉

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/env python
# coding=utf-8
from datetime import datetime,timezone,timedelta
import re
def to_timestamp(info,where):
if not isinstance(info,str) or not isinstance(where,str): #用户错误输入处理
print ("wrong input")
return None
now = datetime.strptime(info,"%Y-%m-%d %H:%M:%S") #格式化时间
temp = re.match(r'^(UTC)([+-])([0-9]+):([0-9]+)',where).groups() #正则匹配分割时间,应该有更简便的办法,我顺便练习下正则
temp = int(temp[1]+temp[2]) #字符串转换成数字
now = now.replace(tzinfo=timezone(timedelta(hours=temp))) #转换成带时区的时间
return now.timestamp() #转换成timestamp

t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00')

assert t1 == 1433121030.0, t1

t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00')

assert t2 == 1433121030.0, t2

print('Pass')

处理base64无等号版编码

请写一个能处理去掉=的 base64 解码函数:

1
2
3
4
5
6
7
8
9
10
11
12
# -*- coding: utf-8 -*-
import base64
def safe_base64_decode(s):
----
pass
----
# 测试:
assert b'abcd' == safe_base64_decode(b'YWJjZA=='),
safe_base64_decode('YWJjZA==')
assert b'abcd' == safe_base64_decode(b'YWJjZA'),
safe_base64_decode('YWJjZA')
print('Pass')
  • 题目不难。。然后我发觉题目给的测试是有误的,assert加逗号,后面那部分出错后是不会执行的,他的想法是对的,然而写法是错的
  • 然后python3我代码没过,python2过了,具体细节待研究
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    #!/usr/bin/env python
    # coding=utf-8
    import base64
    def safe_base64_decode(s):
    length = len(s)
    result = ""
    if length%4 == 0 :
    result = base64.b64decode(s)
    else:
    result = base64.b64decode(str(s) + (length%4)*'=')
    return result
    assert b'abcd' == safe_base64_decode(b'YWJjZA==')

    safe_base64_decode('YWJjZA==')

    assert b'abcd' == safe_base64_decode(b'YWJjZA')

    safe_base64_decode('YWJjZA')

    print('Pass')

struct的使用

练习:请编写一个 bmpinfo.py,可以检查任意文件是否是位图文件,如果是,打印出图片大小和颜色数。

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python
# coding=utf-8
import struct
def judge(filename):
with open(filename,'rb') as f:
data = f.read(30)
temp = struct.unpack('<ccIIIIIIHH',data)
if temp[0] == 'B' and (temp[1]=='M' or temp[1]=='A'):
print('size :{}*{},color:{}'.format(temp[6],temp[7],temp[9]))
else:
raise RuntimeError('wrong file')

judge('1.py')

本文作者:NoOne
本文地址https://noonegroup.xyz/posts/98ab9219/
版权声明:转载请注明出处!