python 时间相互转换
# -*- encoding=utf-8 -*-
import time
import calendar
import datetime
from dateutil.relativedelta import relativedelta
TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
class TimeUtil(object):
@classmethod
def day_range(cls, dt=None):
"""获取天级时间范围"""
dt = dt or datetime.datetime.now()
day_st = datetime.datetime(year=dt.year, month=dt.month, day=dt.day)
day_et = day_st + datetime.timedelta(days=1)
return day_st, day_et
@classmethod
def week_range(cls, dt=None):
"""获取周级时间范围"""
dt = dt or datetime.datetime.now()
week_st = dt - datetime.timedelta(days=dt.weekday())
week_st = datetime.datetime(year=week_st.year, month=week_st.month, day=week_st.day)
week_et = week_st + datetime.timedelta(days=7)
return week_st, week_et
@classmethod
def month_range(cls, dt=None):
"""获取月级时间范围"""
dt = dt or datetime.datetime.now()
_, dayn = calendar.monthrange(dt.year, dt.month)
month_st = datetime.datetime(year=dt.year, month=dt.month, day=1)
month_et = month_st + datetime.timedelta(days=dayn)
return month_st, month_et
@classmethod
def now_dt(cls, dt=None, years=0, months=0, days=0, seconds=0):
"""获取days天后的时间"""
dt = dt or datetime.datetime.now()
if any([years, months, days, seconds]):
dt += relativedelta(years=years, months=months, days=days, seconds=seconds)
return dt
@classmethod
def now_ts(cls):
return int(time.time())
@classmethod
def dt_2int(cls, dt):
if not dt:
return 0
return int(time.mktime(dt.timetuple()))
@classmethod
def int_2dt(cls, tm):
return datetime.datetime.fromtimestamp(tm)
@classmethod
def int_2str(cls, mt, fmt=TIME_FORMAT):
return cls.int_2dt(mt).strftime(fmt)
@classmethod
def min_dt(cls):
return datetime.datetime(1970, 1, 1)
@classmethod
def str_2dt(cls, time_str, _format=TIME_FORMAT):
try:
return datetime.datetime.strptime(time_str, _format)
except Exception:
return False
@classmethod
def dt_2str(cls, dt, _format=TIME_FORMAT):
try:
assert isinstance(dt, datetime.datetime)
if dt == cls.min_dt():
return ""
return dt.strftime(_format)
except Exception:
return False
@classmethod
def timestamp(cls, dt):
# 将时间转为时间戳
try:
assert isinstance(dt, datetime.datetime)
return datetime.datetime.timestamp(dt)
except Exception:
return False