Posted on 2020-03-25 18:47
魔のkyo 阅读(175)
评论(0) 编辑 收藏 引用
下面全部函数命名格式为a2b,a、b为如下类型中的一种
timestamp: float类型 1970-1-1至今的秒数,如time.time()的返回值
str: 时间或日期的字符串表示
datetime: datetime.datetime类型的日期加时间
date: datetime.date类型的日期
time: datetime.time类型的时间
import time
from datetime import datetime, date
def str2timestamp(s, fmt=r"%Y-%m-%d %H:%M:%S"):
return time.mktime(time.strptime(s, fmt))
def timestamp2str(ts, fmt=r"%Y-%m-%d %H:%M:%S"):
return datetime.fromtimestamp(ts).strftime(fmt)
def datetime2timestamp(dt):
return dt.timestamp()
def timestamp2datetime(ts):
return datetime.fromtimestamp(ts)
def datetime2str(dt, fmt=r"%Y-%m-%d %H:%M:%S"):
return dt.strftime(fmt)
def str2datetime(s, fmt=r"%Y-%m-%d %H:%M:%S"):
return datetime.strptime(s, fmt)
def date2str(d, fmt=r"%Y-%m-%d"):
return d.strftime(fmt)
def str2date(s, fmt=r"%Y-%m-%d"):
return str2datetime(s, fmt).date()
def date2timestamp(d):
fmt = r"%Y-%m-%d"
return str2timestamp(date2str(d, fmt), fmt)
def timestamp2date(ts):
return date.fromtimestamp(ts)
def date2datetime(d):
fmt = r"%Y-%m-%d"
return str2datetime(date2str(d, fmt), fmt)
def datetime2date(dt):
return dt.date()
def str2time(s, fmt=None):
if not fmt:
if len(s) == 8:
fmt = "%H:%M:%S"
elif len(s) == 5:
fmt = "%H:%M"
return datetime.strptime(s, fmt).time()
def time2str(t, fmt="%H:%M:%S"):
return t.strftime(fmt)