python 开源日期时间转换函数工具集【dtutils】

前提

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'))#相差某个时间后的日期时间

结语

函数名字好记,使用相当方便的。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值