python: conversión de tiempo


#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)) 




Supongo que te gusta

Origin blog.csdn.net/zhizhengguan/article/details/130426433
Recomendado
Clasificación