Python将字符串转换为datetime

有这样一些字符串:

'1710903685'
'20240320110125'
'2024-03-20 11:01:25'

要转换成Python的datetime

代码如下:

import functools
import re
from datetime import datetime, timedelta
from typing import Union

# pip install python-dateutil
from dateutil import parser


def convert_zone(func):
    @functools.wraps(func)
    def deco(*args, **kw):
        is_utc = kw.pop("is_utc", False)
        v = func(*args, **kw)
        if is_utc:
            v += timedelta(hours=8)
        return v

    return deco


@convert_zone
def parse_time(s: Union[int, float, str], *, is_utc=False) -> datetime:
    """将字符串或数值转换为datetime

    Usage::
        >>> from datetime import datetime
        >>> parse_time(1710903685)
        datetime.datetime(2024, 3, 20, 11, 1, 25)
        >>> parse_time('1710903685')
        datetime.datetime(2024, 3, 20, 11, 1, 25)
        >>> parse_time('2024-03-20 11:01:25')
        datetime.datetime(2024, 3, 20, 11, 1, 25)
        >>> parse_time('20240320110125')
        datetime.datetime(2024, 3, 20, 11, 1, 25)
        >>> parse_time('20240320110125', is_utc=True)
        datetime.datetime(2024, 3, 20, 19, 1, 25)
        >>> parse_time(1710903685) == parse_time('1710903685') == parse_time('2024-03-20 11:01:25') == datetime(2024, 3, 20, 11, 1, 25)
        True
        >>> parse_time(1710903685.780527) == parse_time('1710903685.780527') == parse_time('2024-03-20 11:01:25.780527') == datetime(2024, 3, 20, 11, 1, 25, 780527)
        True
        >>> now = datetime.now()
        >>> timestamp = now.timestamp()
        >>> parse_time(str(now)) == now == parse_time(str(timestamp)) == parse_time(timestamp)
        True
        >>> try:
        ...     parse_time('invalid time')
        ... except ValueError as e:
        ...     print(e)
        ...
        Can't parse s='invalid time' to datetime
    """
    if isinstance(s, (int, float)):
        return datetime.fromtimestamp(s)
    if s.isdigit():
        try:
            return datetime.fromtimestamp(int(s))
        except ValueError:
            pass
    if re.match(r"\d+\.\d+$", s):
        return datetime.fromtimestamp(float(s))
    try:
        return parser.parse(s)
    except parser.ParserError as e:
        raise ValueError(f"Can't parse {s=} to datetime") from e


def _test():
    import doctest

    doctest.testmod(verbose=True)


if __name__ == "__main__":  # pragma: no cover
    _test()

函数和单元测试都写好后,发现有些字符串是UTC时间,于是增加了装饰器和is_utc参数来转成北京时间.

单元测试结果如下:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值