概述
文章目录
- 前提
- 工具存放位置
- 提供的函数有
- 安装使用
- 使用示例
- 结语
前提
python中常用的日期时间转换工具有datetime和time,用法很详细复杂,复杂到每次本人使用的时候必须对照着文档使用。
特别是在获取当前日期时间,日前时间转换成时间戳,时间戳转换成日期时间,时间差等时,必须要对照文档,麻烦。
现在封装了最最常用的函数,希望大家能不用文档直接使用。
工具存放位置
工具存放到了github,作为一个小小的开源项目,欢迎使用发现指正。
github地址
提供的函数有
def nowdatetime(type=“%Y-%m-%d %H:%M:%S”)
获取当前日期时间
:param type: 输出的日期时间格式,默认是"%Y-%m-%d %H:%M:%S",要显示毫秒"%Y-%m-%d %H:%M:%S.%f"
:return: 日期时间str
def nowdate(type=“%Y-%m-%d”)
获取当前日期
:param type: 输出的日期格式,默认是"%Y-%m-%d"
:return: 日期str
def nowtime(type=“%H:%M:%S”)
获取当前时间
:param type: 输出的时间格式,默认是"%H:%M:%S",要显示毫秒"%H:%M:%S.%f"
:return: 时间str
def nowtimetag()
获取当前日期时间对应的时间戳(秒级)
:return: 秒级时间戳int
def nowmillitimetag()
获取当前日期时间对应的时间戳(毫秒级)
:return:毫秒级时间戳int
def timetag2datetime(timetag, type=“%Y-%m-%d %H:%M:%S”)
时间戳转换成日期时间
:param timetag:时间戳,int,float,秒级或毫秒级时间戳都行
:param type:转换的日期时间格式,默认"%Y-%m-%d %H:%M:%S"
:return:指定格式的日期时间str
def datetime2timetag(strdatetime,type=“%Y-%m-%d %H:%M:%S”)
日期时间转换成秒级时间戳
:param strdatetime: str,日期时间
:param type: str,传入的日期时间的格式,默认是"%Y-%m-%d %H:%M:%S"
:return: int,时间戳
def datetime2millitimetag(strdatetime,type=“%Y-%m-%d %H:%M:%S.%f”)
日期时间转换成毫秒级时间戳
:param strdatetime: str,日期时间
:param type: str,传入的日期时间的格式,默认是"%Y-%m-%d %H:%M:%S.%f"
:return: int,时间戳
def deltadatetime(strdatetime=None, days=0, hours=0, minutes=0, seconds=0, milliseconds=0,type=“%Y-%m-%d %H:%M:%S”)
获取某个时间间隔后的日期时间
:param strdatetime: 参照日期时间,如果不填则使用当前日期时间
:param days:间隔的天数,默认0
:param hours:间隔小时数,默认0
:param minutes:间隔的分钟数,默认0
:param seconds:间隔的秒数,默认0
:param milliseconds:间隔的毫秒数,默认0
:param type:参照日期时间格式和输出的日期时间格式
:return:str
安装使用
pip install dtutils
使用示例
from dtutils import *
dir(dtutils) #查看所有方法
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'datetime', 'datetime2millitimetag', 'datetime2timetag', 'deltadatetime', 'nowdate', 'nowdatetime', 'nowmillitimetag', 'nowtime', 'nowtimetag', 'time', 'timetag2datetime']
from dtutils import *
if __name__=="__main__":
print(nowdatetime('%Y-%m-%d %H:%M:%S.%f'))#当前日期时间,精确到毫秒
print(nowdate())#当前日期
print(nowtime())#当前时间
print(nowtimetag())#当前秒级时间戳
print(nowmillitimetag())#当前毫秒级时间戳
print(timetag2datetime(nowmillitimetag()))#时间戳转成日期时间
time.sleep(5)
print(timetag2datetime(nowtimetag()))#时间戳转成日期时间
nowstr = timetag2datetime(nowmillitimetag(), '%Y%m%d %H%M%S.%f')
print(nowstr)
print(datetime2timetag(nowstr,type='%Y%m%d %H%M%S.%f'))#日期时间转成秒级时间戳
print(datetime2millitimetag(nowstr, type='%Y%m%d %H%M%S.%f'))#日期时间转成毫秒级时间戳
print(deltadatetime(nowstr,hours=-10,seconds=-150,type='%Y%m%d %H%M%S.%f'))#相差某个时间后的日期时间
结语
函数名字好记,使用相当方便的。
最后
以上就是土豪月饼为你收集整理的python 日期时间转换函数工具集前提工具存放位置提供的函数有安装使用使用示例结语的全部内容,希望文章能够帮你解决python 日期时间转换函数工具集前提工具存放位置提供的函数有安装使用使用示例结语所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复