68 lines
2.0 KiB
Python
68 lines
2.0 KiB
Python
import datetime
|
||
import re
|
||
|
||
|
||
def current():
|
||
return datetime.datetime.now()
|
||
|
||
|
||
def current_timestamp():
|
||
return int(datetime.datetime.now().timestamp() * 1000)
|
||
|
||
|
||
def is_time_difference_greater_than(timestamp1, timestamp2, hours=0, minutes=0, seconds=0, milliseconds=0):
|
||
"""
|
||
判断两个时间戳的时间差是否大于指定的小时、分钟和秒数
|
||
|
||
参数:
|
||
timestamp1 (int): 第一个时间戳
|
||
timestamp2 (int): 第二个时间戳
|
||
hours (int): 要比较的小时数,默认是0小时
|
||
minutes (int): 要比较的分钟数,默认是0分钟
|
||
seconds (int): 要比较的秒数,默认是0秒
|
||
|
||
返回:
|
||
bool: 如果时间差大于指定的小时、分钟和秒数返回True,否则返回False
|
||
"""
|
||
# 将时间戳转换为 datetime 对象
|
||
time1 = datetime.fromtimestamp(timestamp1) / 1000.0
|
||
time2 = datetime.fromtimestamp(timestamp2) / 1000.0
|
||
|
||
# 计算时间差
|
||
time_difference = abs(time2 - time1)
|
||
|
||
# 计算指定的时间差值
|
||
threshold = datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds, milliseconds=milliseconds)
|
||
|
||
# 判断时间差是否大于指定的时间
|
||
return time_difference > threshold
|
||
|
||
|
||
def parse_time_string(time_str):
|
||
# 定义支持的时间单位
|
||
time_units = {
|
||
'd': 'days',
|
||
'h': 'hours',
|
||
'min': 'minutes',
|
||
's': 'seconds',
|
||
'ms': 'milliseconds'
|
||
}
|
||
|
||
# 使用正则表达式匹配数字和单位的模式
|
||
matches = re.findall(fr"(\d+)({'|'.join(time_units.keys())})", time_str)
|
||
|
||
if not matches:
|
||
raise ValueError(f"Invalid time string format: {time_str}")
|
||
|
||
result = {}
|
||
for value, unit in matches:
|
||
if unit in time_units:
|
||
result[time_units[unit]] = int(value)
|
||
else:
|
||
raise ValueError(f"Unsupported unit: {unit}")
|
||
|
||
return result
|
||
|
||
def to_milliseconds(days=0, hours=0, minutes=0, seconds=0, milliseconds=0):
|
||
return days * 24 * 60 * 60 * 1000 + hours * 60 * 60 * 1000 + minutes * 60 * 1000 + seconds * 1000 + milliseconds
|