Python入门系列(八)日期时间、数学、json
日期时间
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
Python入门系列(八)日期时间、数学、json的更多相关文章
- 微软云平台windows azure入门系列八课程
		
微软云平台windows azure入门系列八课程: Windows Azure入门教学系列 (一): 创建第一个WebRole程序与部署 Windows Azure入门教学系列 (二): 创建第一个 ...
 - C语言高速入门系列(八)
		
C语言高速入门系列(八) C语言位运算与文件 本章引言: 在不知不觉中我们的C高速入门系列已经慢慢地接近尾声了,而在这一节中,我们会对 C语言中的位运算和文件进行解析,相信这两章对于一些人来说是陌生的 ...
 - Python 入门之  内置模块 -- 序列化模块(json模块、pickle模块)
		
Python 入门之 内置模块 -- 序列化模块(json模块.pickle模块) 1.序列化 Python中这种序列化模块有三种:  json模块 :  不同语言都遵循的一种数据转化格式,即不同 ...
 - Python基础教程系列目录,最全的Python入门系列教程!
		
Python是一个高层次的结合了解释性.编译性.互动性和面向对象的脚本语言. 在现在的工作及开发当中,Python的使用越来越广泛,为了方便大家的学习,Linux大学 特推出了 <Python基 ...
 - 08. Web大前端时代之:HTML5+CSS3入门系列 ~ QQ空间时间轴
		
Web大前端时代之:HTML5+CSS3入门系列:http://www.cnblogs.com/dunitian/p/5121725.html 大前端系列,主要就是使用CSS3.0来实现,注释我已经打 ...
 - Python入门系列【附】进阶教程
		
如题,本篇将讲解Python提升之路:Python作为语法简单易学的语言,入门容易精通却很难,这是共识,那么为什么会有这样的共识?精通Python的难度在哪里? Python拥有简单.形象.直观的语法 ...
 - Python入门基础学习(时间模块,随机模块)
		
Python基础学习笔记(六) time模块: 时间的三种表示方法: 1.格式化字符串 2.时间戳 用来表示和1970年的时间间隔,单位为s 3.元组 struct_time 9个元素 time的st ...
 - 大爽Python入门教程 1-1 简单的数学运算
		
大爽Python入门公开课教案 点击查看教程总目录 1 使用pycharm建立我们的第一个项目 打开pycharm,点击菜单栏,File->New Project 在Location(项目地址) ...
 - Unix/Linux环境C编程入门教程(28)  日期时间那些事儿
		
记得这个专题第一篇我们写过一个程序运行时间的程序,采用库函数提供的clock()模拟做程序测试.本篇介绍的函数也是和时间相关,但是没有clock的细致,而是提供的系统时间和日期. 1.asctime( ...
 
随机推荐
- awk运用三维数组进行插值获得任意经纬度处的水层沉积层地壳厚度
			
awk三维数组与插值 目的:给定经纬度,获得该点地下的冰层水层沉积层和地壳的厚度 实现:awk一行命令 下载Crust1.0模型 该数据集的详细介绍见官网. 解压后有几个文件:crust1.vp,cr ...
 - Django cors跨域问题
			
Django cors跨域问题 前后端分离项目中的跨域问题 即同源策略 同源策略:同源策略/SOP(Same origin policy)是一种约定,由 Netscape 公司 1995 年引入浏览器 ...
 - 一文理解OpenStack网络
			
摘要:如果你能理解OpenStack的网络,那么对于其他云平台的网络,应该也可以通过分析后理解掌握了. 本文分享自华为云社区<<跟唐老师学习云网络> - OpenStack网络实现& ...
 - 一个bug肝一周...忍不住提了issue
			
导航 Socket.IO是什么 Socket.IO的应用场景 为什么选socket.io-client-java 实战案例 参考 本文首发于智客工坊-<socket.io客户端向webserve ...
 - C# / VB.NET 将Html转为Word
			
本文分享以C#程序代码为例,实现将Html文件转换Word文档的方法(附VB.NET代码).在实际转换场景中可参考本文的方法,转换前,请按照如下方法引用Word API的dll文件到Visual St ...
 - Python 数据科学手册:读书笔记概论
			
为防止遗忘,在空闲时间将读书的笔记开始按照章节进行概括总结(2022.1.1): 第二章:NumPy 入门 第三章:Pandas 数据处理 第四章:Matplotlib 数据可视化 第五章:机器学习 ...
 - HashMap设计原理与实现(下篇)200行带你写自己的HashMap!!!
			
HashMap设计原理与实现(下篇)200行带你写自己的HashMap!!! 我们在上篇文章哈希表的设计原理当中已经大体说明了哈希表的实现原理,在这篇文章当中我们将自己动手实现我们自己的HashMap ...
 - 用KVM安装MacOS/OSX
			
基本步骤按照大牛的步骤https://github.com/kholia/OSX-KVM 黑果镜像建议用黑果小兵的:macOS Big Sur(我试过,大牛的更卡),里面的双EFI就很够用. 将镜像名 ...
 - linux docker .net core  从建立网站到预览
			
docker的安装在网上一搜一大把,windows安装的就是exe双击,linux安装需要执行语句 ps:需要准备xftp.xshell.vs 2019.linux服务器.docker账号密码 例如: ...
 - CF Edu Round 131 简要题解 (ABCD)
			
A 分类讨论即可 . using namespace std; typedef long long ll; typedef pair<int, int> pii; int main() { ...