相对时间变时间戳

相对时间变时间戳

import re
from datetime import datetime, timedelta

from loguru import logger

# 定义一个映射表,将汉字数字转换为对应的整数
CHINESE_NUMBERS = {
    '一': 1, '二': 2, '三': 3, '四': 4, '五': 5,
    '六': 6, '七': 7, '八': 8, '九': 9, '十': 10,
    '两': 2
}


def chinese_to_int(chinese_number: str) -> int:
    """
    将汉字数字转换成整数。
    只支持小于100的汉字数字。
    """
    if chinese_number.isdigit():  # 如果是纯数字直接返回
        return int(chinese_number)

    total = 0
    unit = 1
    num = 0
    for char in reversed(chinese_number):
        if char == '十':  # 如果是 "十" 字,处理十位
            unit = 10
            if num == 0:  # 如果 "十" 前面没有数字,表示是 "十" 而非 "X十"
                num = 1
            total += num * unit
            num = 0
        else:
            if char in CHINESE_NUMBERS:  # 如果是普通数字,直接加
                num = CHINESE_NUMBERS[char]
            total += num * unit
            num = 0
            unit = 1
    return total


def convert_relative_time_to_timestamp(relative_time: str) -> int:
    """
    将相对时间(如"2天前发布","一小时前发布")转换为时间戳。
    """
    # 获取当前时间
    now = datetime.now()

    # 处理并解析输入字符串
    if "天前" in relative_time:
        match = re.search(r'([\d一二三四五六七八九十两]+)天前', relative_time)
        if match:
            days = chinese_to_int(match.group(1))
            result_time = now - timedelta(days=days)
        else:
            raise ValueError("无法解析 '天前' 时间格式")

    elif "小时前" in relative_time:
        match = re.search(r'([\d一二三四五六七八九十两]+)小时前', relative_time)
        if match:
            hours = chinese_to_int(match.group(1))
            result_time = now - timedelta(hours=hours)
        else:
            raise ValueError("无法解析 '小时前' 时间格式")

    elif "分钟前" in relative_time:
        match = re.search(r'([\d一二三四五六七八九十两]+)分钟前', relative_time)
        if match:
            minutes = chinese_to_int(match.group(1))
            result_time = now - timedelta(minutes=minutes)
        else:
            raise ValueError("无法解析 '分钟前' 时间格式")

    else:
        raise ValueError("无法识别的时间格式: " + relative_time)

    # 返回时间戳
    return int(result_time.timestamp())


# 测试
def test_convert_relative_time_to_timestamp():
    test_key = ["2天前发布", "一小时前发布", "十五分钟前发布", "两天前发布"]
    for item in test_key:
        logger.info({item: convert_relative_time_to_timestamp(item)})


test_convert_relative_time_to_timestamp()

""" 输出结果
2025-04-27 14:57:48.874 | INFO     | __main__:test_convert_relative_time_to_timestamp:84 - {'2天前发布': 1745564268}
2025-04-27 14:57:48.874 | INFO     | __main__:test_convert_relative_time_to_timestamp:84 - {'一小时前发布': 1745733468}
2025-04-27 14:57:48.874 | INFO     | __main__:test_convert_relative_time_to_timestamp:84 - {'十五分钟前发布': 1745736168}
2025-04-27 14:57:48.874 | INFO     | __main__:test_convert_relative_time_to_timestamp:84 - {'两天前发布': 1745564268}
"""
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值