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

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 @   Eliphaz  阅读(194)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示