payment/payment_backend/utils/datetime.py

73 lines
2.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import datetime
import re
def current():
return datetime.datetime.now()
def current_timestamp():
return int(datetime.datetime.now().timestamp() * 1000)
def timestamp2datetime(timestamp):
return datetime.datetime.fromtimestamp(timestamp / 1000.0)
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 = timestamp2datetime(timestamp1)
time2 = timestamp2datetime(timestamp2)
# 计算时间差
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