Python入門系列(八)日期時間、數學、json
- 2022 年 9 月 2 日
- 筆記
- Python, python入門系列
日期時間
Python中的日期本身不是數據類型,但我們可以導入一個名為datetime的模組,將日期作為日期對象使用。
import datetime
x = datetime.datetime.now()
print(x)
日期輸出
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
創建日期對象
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
strftime()方法
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
Directive | Description | Example |
---|---|---|
%a | Weekday, short version | Wed |
%A | Weekday, full version | Wednesday |
%w | Weekday as a number 0-6, 0 is Sunday | 3 |
%d | Day of month 01-31 | 31 |
%b | Month name, short version | Dec |
%B | Month name, full version | December |
%m | Month as a number 01-12 | 12 |
%y | Year, short version, without century | 18 |
%Y | Year, full version | 2018 |
%H | Hour 00-23 | 17 |
%I | Hour 00-12 | 05 |
%p | AM/PM | PM |
%M | Minute 00-59 | 41 |
%S | Second 00-59 | 08 |
%f | Microsecond 000000-999999 | 548513 |
%z | UTC offset | +0100 |
%Z | Timezone | CST |
%j | Day number of year 001-366 | 365 |
%U | Week number of year, Sunday as the first day of week, 00-53 | 52 |
%W | Week number of year, Monday as the first day of week, 00-53 | 52 |
%c | Local version of date and time | Mon Dec 31 17:41:00 2018 |
%C | Century | 20 |
%x | Local version of date | 12/31/18 |
%X | Local version of time | 17:41:00 |
%% | A % character | % |
%G | ISO 8601 year | 2018 |
%u | ISO 8601 weekday (1-7) | 1 |
數學
min()和max()函數可用於查找可迭代中的最低或最高值
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
函數的作用是:返回指定數字的絕對(正)值
x = abs(-7.25)
print(x)
pow(x,y)函數將x的值返回到y(xy)的冪。
# Return the value of 4 to the power of 3 (same as 4 * 4 * 4)
x = pow(4, 3)
print(x)
數學模組
import math
x = math.sqrt(64)
print(x)
ceil()方法將一個數字向上舍入到其最接近的整數,然後進行數學運算。floor()方法將數字向下舍入到最接近的整數,並返回結果
import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
pi常量,返回pi的值(3.14…)
import math
x = math.pi
print(x)
JSON
從JSON轉換為Python
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
從Python轉換為JSON
import json
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
您可以將以下類型的Python對象轉換為JSON字元串.
當您從Python轉換為JSON時,Python對象將轉換成JSON(JavaScript)等價物
Python | JSON |
---|---|
dict | Object |
list | Array |
tuple | Array |
str | String |
int | Number |
float | Number |
True | true |
False | false |
None | null |
格式化結果
使用縮進參數定義縮進的數量
json.dumps(x, indent=4)
您還可以定義分隔符,默認值為(「,」,「:」,這意味著使用逗號和空格分隔每個對象,使用冒號和空格分隔鍵和值
json.dumps(x, indent=4, separators=(". ", " = "))
json_dumps()方法有參數來對resu中的鍵進行排序
json.dumps(x, indent=4, sort_keys=True)
正則表達式
Python有一個名為re的內置包,可用於處理正則表達式。
import re
正則表達式函數
Function | Description |
---|---|
findall | Returns a list containing all matches |
search | Returns a Match object if there is a match anywhere in the string |
split | Returns a list where the string has been split at each match |
sub | Replaces one or many matches with a string |
元字元是具有特殊含義的字元
Character | Description | Example |
---|---|---|
[] | A set of characters | “[a-m]” |
\ | Signals a special sequence (can also be used to escape special characters) | “\d” |
. | Any character (except newline character) | “he..o” |
^ | Starts with | “^hello” |
$ | Ends with | “planet$” |
* | Zero or more occurrences | “he.*o” |
+ | One or more occurrences | “he.+o” |
? | Zero or one occurrences | “he.?o” |
{} | Exactly the specified number of occurrences | “he.{2}o” |
| | Either or | “falls|stays” |
() | Capture and group |
特殊序列
Character | Description | Example |
---|---|---|
\A | Returns a match if the specified characters are at the beginning of the string | “\AThe” |
\b | Returns a match where the specified characters are at the beginning or at the end of a word (the “r” in the beginning is making sure that the string is being treated as a “raw string”) | r”\bain” r”ain\b” |
\B | Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word (the “r” in the beginning is making sure that the string is being treated as a “raw string”) | r”\Bain” r”ain\B” |
\d | Returns a match where the string contains digits (numbers from 0-9) | “\d” |
\D | Returns a match where the string DOES NOT contain digits | “\D” |
\s | Returns a match where the string contains a white space character | “\s” |
\S | Returns a match where the string DOES NOT contain a white space character | “\S” |
\w | Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) | “\w” |
\W | Returns a match where the string DOES NOT contain any word characters | “\W” |
\Z | Returns a match if the specified characters are at the end of the string | “Spain\Z” |
集合是一對方括弧[]內的一組字元,具有特殊含義
Set | Description |
---|---|
[arn] | Returns a match where one of the specified characters (a , r , or n ) is present |
[a-n] | Returns a match for any lower case character, alphabetically between a and n |
[^arn] | Returns a match for any character EXCEPT a , r , and n |
[0123] | Returns a match where any of the specified digits (0 , 1 , 2 , or 3 ) are present |
[0-9] | Returns a match for any digit between 0 and 9 |
[0-5][0-9] | Returns a match for any two-digit numbers from 00 and 59 |
[a-zA-Z] | Returns a match for any character alphabetically between a and z , lower case OR upper case |
[+] | In sets, + , * , . , ` |
findall()函數的作用是:返回一個包含所有匹配項的列表。
import re
txt = "The rain in Spain"
x = re.findall("ai", txt)
print(x)
該列表按找到的順序包含匹配項。
如果未找到匹配項,則返回空列表
import re
txt = "The rain in Spain"
x = re.findall("Portugal", txt)
print(x)
search()函數的作用是:在字元串中搜索匹配項,如果存在匹配項,則返回匹配對象。
import re
txt = "The rain in Spain"
x = re.search("\s", txt)
print("The first white-space character is located in position:", x.start())
split()函數的作用是:返回一個列表,其中字元串在每次匹配時被拆分
import re
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)
可以通過指定maxsplit參數來控制出現次數
import re
txt = "The rain in Spain"
x = re.split("\s", txt, 1)
print(x)
sub()函數的作用是:用您選擇的文本替換匹配項
import re
txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x) # The9rain9in9Spain
您可以通過指定count參數來控制替換的數量
import re
txt = "The rain in Spain"
x = re.sub("\s", "9", txt, 2)
print(x)
匹配對象是包含有關搜索和結果的資訊的對象。
注意:如果沒有匹配,將返回值None,而不是match對象。
.span()
返回包含匹配的開始位置和結束位置的元組。
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.span()) # (12, 17)
.string
返回傳遞到函數中的字元串
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.string) # The rain in Spain
.group()
返回字元串中存在匹配項的部分
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.group()) # Spain
您的關注,是我的無限動力!
公眾號 @生活處處有BUG