98 lines
2.8 KiB
Python
98 lines
2.8 KiB
Python
# -*- coding: UTF-8 -*-
|
||
"""
|
||
@Project -> File :IoD_data_analysis_tool -> timeutil
|
||
@IDE :PyCharm
|
||
@Author :rengengchen
|
||
@Date :2022/4/26 10:02
|
||
@Desc :
|
||
"""
|
||
import datetime
|
||
import types
|
||
import typing
|
||
|
||
from dateutil import parser
|
||
|
||
|
||
class cnparserinfo(parser.parserinfo):
|
||
"""
|
||
匹配中文日期格式
|
||
用法:
|
||
from dateutil import parser
|
||
parser.parse('1998年12月11日 8点20分30秒', cnparserinfo())
|
||
"""
|
||
parser.parserinfo.JUMP.extend('年月日')
|
||
WEEKDAYS = [list(weekdays) for weekdays in parser.parserinfo.WEEKDAYS]
|
||
WEEKDAYS[0].extend(('星期一', '周一'))
|
||
WEEKDAYS[1].extend(('星期二', '周二'))
|
||
WEEKDAYS[2].extend(('星期三', '周三'))
|
||
WEEKDAYS[3].extend(('星期四', '周四'))
|
||
WEEKDAYS[4].extend(('星期五', '周五'))
|
||
WEEKDAYS[5].extend(('星期六', '周六'))
|
||
WEEKDAYS[6].extend(('星期天', '周日', '周天', '周末'))
|
||
WEEKDAYS = [tuple(weekdays) for weekdays in WEEKDAYS]
|
||
|
||
# MONTHS = [list(months) for months in parser.parserinfo.MONTHS]
|
||
# MONTHS[0].extend(('一月', '1月'))
|
||
# MONTHS[1].extend(('二月', '2月'))
|
||
# MONTHS[2].extend(('三月', '3月'))
|
||
# MONTHS[3].extend(('四月', '4月'))
|
||
# MONTHS[4].extend(('五月', '5月'))
|
||
# MONTHS[5].extend(('六月', '6月'))
|
||
# MONTHS[6].extend(('七月', '7月'))
|
||
# MONTHS[7].extend(('八月', '8月'))
|
||
# MONTHS[8].extend(('九月', '9月'))
|
||
# MONTHS[9].extend(('十月', '10月'))
|
||
# MONTHS[10].extend(('十一月', '11月'))
|
||
# MONTHS[11].extend(('十二月', '12月'))
|
||
# MONTHS = [tuple(months) for months in MONTHS]
|
||
|
||
HMS = [list(hms) for hms in parser.parserinfo.HMS]
|
||
HMS[0].extend('时点')
|
||
HMS[1].append('分')
|
||
HMS[2].append('秒')
|
||
HMS = [tuple(hms) for hms in HMS]
|
||
|
||
AMPM = [list(ampm) for ampm in parser.parserinfo.AMPM]
|
||
AMPM[0].append('上午')
|
||
AMPM[1].append('下午')
|
||
AMPM = [tuple(ampm) for ampm in AMPM]
|
||
|
||
def __init__(self, dayfirst=False, yearfirst=False):
|
||
super().__init__(dayfirst, yearfirst)
|
||
|
||
|
||
def utctimestamp():
|
||
"""
|
||
@return: utc时间戳
|
||
"""
|
||
return int(datetime.datetime.utcnow().timestamp())
|
||
|
||
|
||
def timestamp2datetime(ts: float):
|
||
return datetime.datetime.fromtimestamp(ts)
|
||
|
||
|
||
def timestamp2str(ts: float, fmt: str = '%F %H:%M:%S'):
|
||
"""
|
||
@param ts: timestamp
|
||
@param fmt: format
|
||
"""
|
||
return datetime.datetime.strftime(timestamp2datetime(ts), fmt)
|
||
|
||
|
||
cnparser = cnparserinfo()
|
||
|
||
|
||
def str2datetime(datetime_str: str, fmt: str = None):
|
||
if fmt:
|
||
return datetime.datetime.strptime(datetime_str, fmt)
|
||
return parser.parse(datetime_str, cnparser)
|
||
|
||
|
||
def int2date(date_int: int):
|
||
return str2datetime(str(date_int), '%Y%m%d')
|
||
|
||
|
||
def date2int(a: typing.Union[datetime.datetime, datetime.date]):
|
||
return int(a.strftime('%Y%m%d'))
|