python:时间转换


#coding=utf-8
import  requests


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

    """
            作用:返回当前秒时间戳
            调用: TimeUtil.now_ts()"""
    @classmethod
    def now_ts(cls):
        return int(time.time())

    """
            作用:  将dt转换为秒时间戳
            调用: TimeUtil.dt_2int(dt)"""
    @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
        

time_dt = TimeUtil.str_2dt("2022-01-01 00:00:00")  #2022-01-01 00:00:00
sec_unix = TimeUtil.dt_2int(time_dt) #1640966400
TimeUtil.int_2dt(sec_unix  ) # 2022-01-01 00:00:00
print(TimeUtil.dt_2int(time_dt)) 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值