涉及日期的常用方法,前几天、后几天、时间戳日期转换等

1.返回本地当前时间
def current_datetime():
    """返回本地当前时间, 包含datetime 格式, 字符串格式, 时间戳格式(str)
    :return: (datetime 格式, 字符串格式, 时间戳格式)
    """
    # 当前时间:datetime 格式
    local_datetime_now = datetime.now()
    # 当前时间:字符串格式
    local_strtime_now = datetime_to_strtime(local_datetime_now)
    # 当前时间:时间戳格式 13位整数
    local_timestamp_now = datetime_to_timestamp(local_datetime_now)
    return local_datetime_now, local_strtime_now, local_timestamp_now


2.返回前第几天的时间
def before_now_datetime(days, fmt, now=None):
    """返回前第几天的时间, 包含datetime 格式, 字符串格式, 时间戳格式
    :return: (datetime 格式, 字符串格式, 时间戳格式)
    """

    if now != None:
        yestoday = now - timedelta(days=days)
        return yestoday.strftime(fmt)
    else:
        now = datetime.now()
        yestoday = now - timedelta(days=days)
        return yestoday.strftime(fmt)

 

3.返回后第几天的时间

def after_now_datetime(days, fmt, now=None):
    """返回后第几天的时间, 包含datetime 格式, 字符串格式, 时间戳格式
    :return: (datetime 格式, 字符串格式, 时间戳格式)
    """

    if now != None:
        yestoday = now + timedelta(days=days)
        return yestoday.strftime(fmt)
    else:
        now = datetime.now()
        yestoday = now + timedelta(days=days)
        return yestoday.strftime(fmt)

4.时间戳转普通时间

def timestamp_to_strtime(timestamp,fmt='%Y-%m-%d %H:%M:%S'):
    """将 10、13 位整数的毫秒时间戳转化成本地普通时间 (字符串格式)
    :param timestamp: 10、13 位整数的毫秒时间戳 (1456402864242)
    :return: 返回字符串格式 {str}'2016-02-25 20:21:04.242000'
    """
    if not timestamp:
        return ''
    if len(str(timestamp)) == 13:
        timestamp = float(timestamp) / 1000.0
    time_str = datetime.fromtimestamp(float(timestamp)).strftime(fmt)
    return time_str
def datetime_to_timestamp(datetime_obj):
    """将本地(local) datetime 格式的时间 (含毫秒) 转为毫秒时间戳
    :param datetime_obj: {datetime}2016-02-25 20:21:04.242000
    :return: 13 位的毫秒时间戳  1456402864242 string 格式
    """
    local_timestamp = str(time.mktime(datetime_obj.timetuple()) * 1000.0 + datetime_obj.microsecond / 1000.0)
    return local_timestamp
def strtime_to_datetime(timestr, fmt):
    """将字符串格式的时间 (含毫秒) 转为 datetiem 格式
    :param timestr: {str}'2016-02-25 20:21:04.242'
    :return: {datetime}2016-02-25 20:21:04.242000
    """
    local_datetime = datetime.strptime(timestr, fmt)
    return local_datetime

 

posted @ 2022-06-28 10:12  Eliphaz  阅读(212)  评论(0)    收藏  举报