python字符串时间戳和时间字符串互转和计算天数月数相差(time,datetime时间库使用)

时间库使用

import datetime
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")  北京时间-8个小时
datetime.date.today().strftime('%Y-%m-%d %H:%M:%S')
utc时间戳 int(datetime.utcnow().timestamp())

日期加xx天之后的日期
datetime.date.today() + datetime.timedelta(days=i)



import time
time.time()
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(time.time())))

时间戳转时间字符串

import time
import datetime

def timestampToStr(timestamp):
    # 时间戳转时间字符串
    if len(str(timestamp))>10:
        timestamp = str(timestamp)[:10]
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(timestamp)))

# 获取当前时间字符串
print(timestampToStr(time.time()))
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

时间戳和时间字符串互转

import datetime
import time

def timestamp(timeformat=None,format = '%Y-%m-%d %H:%M:%S'):
    if timeformat:
        time_tuple = time.strptime(timeformat,format)
        res = time.mktime(time_tuple) #转成时间戳
    else:
        res = time.time()        #获取当前时间戳
    return int(res)
print(timestamp(str(datetime.date.today()+datetime.timedelta(1))+" 08:00:00"))


def timestampToStr(timestamp):
    # 时间戳转时间字符串
    if len(str(timestamp))>10:
        timestamp = str(timestamp)[:10]
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(timestamp)))

相差秒数转天数,小时数,分钟数,秒数

#相差秒数转天数,小时数,分钟数,秒数
def changeTime(allTime):
    import math
    day = 24*60*60
    hour = 60*60
    min = 60
    if allTime <60:
        return  "%d sec"%math.ceil(allTime)
    elif  allTime > day:
        days = divmod(allTime,day)
        return "%d days, %s"%(int(days[0]),changeTime(days[1]))
    elif allTime > hour:
        hours = divmod(allTime,hour)
        return '%d hours, %s'%(int(hours[0]),changeTime(hours[1]))
    else:
        mins = divmod(allTime,min)
        return "%d mins, %d sec"%(int(mins[0]),math.ceil(mins[1]))

计算两个日期天数差/月数差/年数差

import datetime
from dateutil import rrule

def calDaysDiff(d1,d2):
    return abs((d1-d2).days)

def calMonthsDiff(d1,d2):
    if (d2-d1).days>=0:
        return rrule.rrule(rrule.MONTHLY, dtstart=d1, until=d2).count()
    return rrule.rrule(rrule.MONTHLY, dtstart=d2, until=d1).count()


def calYearsDiff(d1,d2):
    if (d2-d1).days>=0:
        return rrule.rrule(rrule.YEARLY, dtstart=d1, until=d2).count()-1
    return rrule.rrule(rrule.YEARLY, dtstart=d2, until=d1).count()-1


d1 = datetime.date(2019, 4, 15)
d2 = datetime.date(2019, 12, 15)
print("days={}".format(calDaysDiff(d1,d2)))
print("months={}".format(calMonthsDiff(d2,d1)))
print("years={}".format(calYearsDiff(d1,d2)))

#遇见闰年的2月29号计算月数和年数会出错
d1 = datetime.date(2016, 2, 29)
d2 = datetime.date(2019, 3, 1)
print("出错! months={}".format(calMonthsDiff(d2,d1)))
print("出错! years={}".format(calYearsDiff(d1,d2)))
链接
[https://www.cnblogs.com/yicaifeitian/p/6895588.html](https://www.cnblogs.com/yicaifeitian/p/6895588.html)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值