- utils.py:
import re
from datetime import datetime
from typing import Union
# pip install python-dateutil
from dateutil import parser
def parse_time(s: Union[int, float, str]) -> 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(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():
return datetime.fromtimestamp(int(s))
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()
标签:11,2024,20,python,datetime,parse,time
From: https://www.cnblogs.com/waketzheng/p/18084880