时间转换常用方法

# -*- coding:utf8 -*-
"""
@ Author: 吕文举 wjlv4
@ File: common_fun.py
@ Time: 2022/9/22
@ Contact: wjlv4@iflytek.com
@ Desc:
"""
import os
from datetime import datetime, timedelta



def str_to_date(st: str, fmt=None, delay: dict = None):
    """
    str转成datetime格式
    :param st: 字符串
    :param fmt: 自定義格式,
    :param delay: 延遲時間 {days:1} 延遲1天
    :return:
    """
    days = 0
    hours = 0
    minutes = 0
    weeks = 0
    if delay:
        for key in delay.keys():
            if key not in ['days', 'hours', 'minutes', 'weeks']:
                raise KeyError(f"{key} should be in ['days','hours','minutes','weeks']")
        days = delay.get('days', 0)
        hours = delay.get('hours', 0)
        minutes = delay.get('minutes', 0)
        weeks = delay.get('weeks', 0)
    if fmt:
        _st = datetime.strptime(st, fmt) + timedelta(days=days, hours=hours, minutes=minutes, weeks=weeks)
    elif '-' in st:  # 2022-09-21
        if len(st) < 11:
            _st = datetime.strptime(st, '%Y-%m-%d') + timedelta(days=days, hours=hours, minutes=minutes, weeks=weeks)
        else:  # 2022-09-21 14:17:24
            _st = datetime.strptime(st, '%Y-%m-%d %H:%M:%S') + timedelta(days=days, hours=hours, minutes=minutes,
                                                                         weeks=weeks)
    elif '/' in st:  # 2022/09/21
        if len(st) < 11:
            _st = datetime.strptime(st, '%Y/%m/%d') + timedelta(days=days, hours=hours, minutes=minutes, weeks=weeks)
        else:  # 2022/09/21 14:17:24
            _st = datetime.strptime(st, '%Y/%m/%d %H:%M:%S') + timedelta(days=days, hours=hours, minutes=minutes,
                                                                         weeks=weeks)
    else:  # 20220921
        _st = datetime.strptime(st, '%Y%m%d') + timedelta(days=days, hours=hours, minutes=minutes, weeks=weeks)
    return _st


def date_to_str(dt: datetime, fmt=None, delay: dict = None):
    """
    str轉成datetime格式
    :param st: 字符串
    :param fmt: 自定義格式,
    :param delay: 延遲時間 {days:1} 延遲1天
    :return:
    """
    days = 0
    hours = 0
    minutes = 0
    weeks = 0
    if delay:
        for key in delay.keys():
            if key not in ['days', 'hours', 'minutes', 'weeks']:
                raise KeyError(f"{key} should be in ['days','hours','minutes','weeks']")
        days = delay.get('days', 0)
        hours = delay.get('hours', 0)
        minutes = delay.get('minutes', 0)
        weeks = delay.get('weeks', 0)
    _td = dt + timedelta(days=days, hours=hours, minutes=minutes, weeks=weeks)
    if fmt:
        _str = datetime.strftime(_td, fmt)
    else:  # 20220921
        _str = datetime.strftime(_td, '%Y-%m-%d %H:%M:%S')
    return _str


def str_to_timestamp(st: str, fmt=None, delay: dict = None, ms: bool = True):
    """
    字符串轉為時間戳
    :param st: 字符串
    :param fmt: 字符串格式
    :param delay: 延時,例如{'days':1,'hours':-3}
    :param ms: 是否毫秒模式
    :return:
    """
    _res = str_to_date(st, fmt=fmt, delay=delay)
    ms = 1000 if ms else 1
    return _res.timestamp() * ms


def timestamp_to_str(ts: [int, float], fmt=None, delay: dict = None, ms: bool = True):
    """
    時間戳轉為字符串
    :param ts: 時間戳
    :param fmt: 字符串格式
    :param delay: 延時,例如{'days':1,'hours':-3}
    :param ms: 是否毫秒模式
    :return:
    """
    ms = 1000 if ms else 1
    ts = ts / ms
    _date = datetime.fromtimestamp(ts)
    _res = date_to_str(_date, fmt)
    return _res


def get_today_ts(delay: dict = None, ms: bool = True):
    """
    默認獲取今天凌晨的時間戳,可自定義格格式和延遲時間
    :return:
    """
    return str_to_timestamp(datetime.strftime(datetime.now(), '%Y-%m-%d'), delay=delay, ms=ms)
posted @ 2022-12-30 10:41  唐大侠的小迷弟  阅读(69)  评论(0编辑  收藏  举报