本文介绍Python3中各种处理时间的库和使用方案
最近更新时间:2023.6.2
最早更新时间:2023.6.2
1. datetime库
官方文档:datetime — Basic date and time types — Python 3.11.3 documentation
datetime.datetime.now()
datetime.datetime.today()
datetime.datetime.strptime(字符串,"%Y-%m-%d")
(第二个入参是时间格式)
代码示例,计算两个日期之间相隔的天数和月数:
import datetime
def days(str1,str2):
date1=datetime.datetime.strptime(str1,"%Y-%m-%d")
date2=datetime.datetime.strptime(str2,"%Y-%m-%d")
num=(date1-date2).days
return num
def months(str1,str2):
year1=datetime.datetime.strptime(str1,"%Y-%m-%d").year
year2=datetime.datetime.strptime(str2,"%Y-%m-%d").year
month1=datetime.datetime.strptime(str1,"%Y-%m-%d").month
month2=datetime.datetime.strptime(str2,"%Y-%m-%d").month
num=(year1-year2)*12+(month1-month2)
return num
print(days('2023-5-18','2023-5-10'))
print(days('2023-5-18','2021-5-10'))
输出:
8
738
2. time库
time.time()
:返回当前时间(float值)time.localtime(secs)
time.sleep(秒数)
:睡眠指定时间
3. JioNLP库:(中文)从文本中提取时间信息
通过正则表达式来提取的。
安装方式:pip install jionlp
时间语义解析 说明文档 · dongrixinyu/JioNLP Wiki · GitHub
在线demo:http://www.jionlp.com/jionlp_online/extract_time
示例代码:
import time
import jionlp as jio
time_text_list = ['2021年前两个季度', '从2018年12月九号到十五号', '2019年感恩节', '每周六上午9点到11点', '30~90日']
for time_text in time_text_list:
print(jio.parse_time(time_text, time_base=time.time()))
输出:
# jionlp - 微信公众号: JioNLP Github: `https://github.com/dongrixinyu/JioNLP`.
# jiojio - `http://www.jionlp.com/jionlp_online/cws_pos` is available for online trial.
# jiojio - Successfully load C funcs for CWS and POS acceleration.
{'type': 'time_span', 'definition': 'accurate', 'time': ['2021-01-01 00:00:00', '2021-06-30 23:59:59']}
{'type': 'time_span', 'definition': 'accurate', 'time': ['2018-12-09 00:00:00', '2018-12-15 23:59:59']}
{'type': 'time_point', 'definition': 'accurate', 'time': ['2019-11-28 00:00:00', '2019-11-28 23:59:59']}
{'type': 'time_period', 'definition': 'accurate', 'time': {'delta': {'day': 7}, 'point': {'time': ['2023-06-03 09:00:00', '2023-06-03 11:00:00'], 'string': '周六上午9点到11点'}}}
{'type': 'time_delta', 'definition': 'blur', 'time': [{'day': 30.0}, {'day': 90.0}]}
可以看文档,time_span大概指时间段(头尾都是具体时间),time_point是时间点,time_period是时间周期,time_delta是时间长度。
4. datefinder库:(英文)从文本中提取时间信息
pypi网址:datefinder · PyPI
pip安装方式:pip install datefinder
示例代码:
dt=list(datefinder.find_dates("ASPLOS会议的官网是https://www.asplos-conference.org/,2023年论文提交截止时间是2022年10月20日。"))
返回一个由datetime对象组成的list。
5. pytz库
有一说一,我其实没看懂这个库在干啥,大概是统一时区之类的?
反正有一些别的包在安装时会顺便要求装上的。
pytz · PyPI