python 对于时间的处理

日期转时间戳
def unix_time(self, dt):
	'''
	日期转时间戳
	:param dt:
	:return:
	'''
	# 转换成时间数组
	timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S")
	# 转换成时间戳
	timestamp = int(time.mktime(timeArray))
	return timestamp
自定义时间格式转换
def dateFormatString(self, timestamp, timeType):
    """
    时间用指定格式显示,比如 年-月-日 转 年/月/日
    """
    # dt = "2020-10-10 22:20:20"
    # 转为数组
    # "%Y-%m-%d %H:%M:%S"
    timeArray = time.strptime(timestamp, timeType)
    # 转为其它显示格式
    customTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
    # print(customTime)  # 2020/10/10 22:20:20
    return customTime
时间戳转日期
def custom_time(self, timestamp, timeTypr):
    # 转换成localtime
    time_local = time.localtime(timestamp)
    # 转换成新的时间格式(2016-05-05 20:28:54)
    dt = time.strftime(timeTypr, time_local)
    return dt
判断是否在n天以内
def isRightDayDate(self, pubdate, rightday):
    '''
    距离现在多少天
    传入的数据格式必须是'%Y-%m-%d %H:%M:%S'
    :return:
    '''
    timeNow = datetime.datetime.now()   ###现在的时间
    pdate = datetime.datetime.strptime(pubdate, '%Y-%m-%d %H:%M:%S')
    if abs((timeNow - pdate).days) < rightday :  # 判断时间间隔天数
        return True
    else:
        return False
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中有多种处理时间的方式,以下是一些常用的方法: 1. 使用datetime模块:datetime模块提供了处理日期和时间的类和函数。例如,可以使用datetime类创建一个表示特定日期和时间的对象,并使用其方法进行各种操作,比如计算日期差异、格式化日期和时间等。 ```python import datetime # 获取当前日期和时间 current_datetime = datetime.datetime.now() print(current_datetime) # 格式化日期和时间 formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S") print(formatted_datetime) # 计算日期差异 delta = datetime.timedelta(days=7) next_week = current_datetime + delta print(next_week) ``` 2. 使用time模块:time模块提供了处理时间的函数,包括获取当前时间、睡眠一段时间等。 ```python import time # 获取当前时间戳 timestamp = time.time() print(timestamp) # 将时间戳转换为日期和时间 converted_datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp)) print(converted_datetime) # 睡眠一段时间 time.sleep(1) # 睡眠1秒 ``` 3. 使用arrow库:arrow是一个功能强大且易于使用的库,提供了更简洁的方式来处理日期和时间。 ```python import arrow # 获取当前日期和时间 current_datetime = arrow.now() print(current_datetime) # 格式化日期和时间 formatted_datetime = current_datetime.format("YYYY-MM-DD HH:mm:ss") print(formatted_datetime) # 计算日期差异 next_week = current_datetime.shift(weeks=1) print(next_week) ``` 这些只是处理时间的一些基本方法,根据不同的需求,还可以使用其他库和方法来进行更复杂的处理

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值