Python时间处理

  • datetime库
import datetime
  • arrow库
import arrow
# 获取当前时间 eg:2019-09-23T23:05:01.144662+08:00
a = arrow.now()
print(a)
# 格式化时间
print(a.format("YYYY-MM-DD HH:mm:ss"))
# 获取当前日期 eg:2019-09-23
print(a.date())
# 获取当前时分秒 eg:23:06:50.481176
print(a.time())

# 获取上一个月
last_month = a.shift(months=-1).format("YYYYMMDD")
print(last_month)

# 获取当月最后一天 eg:2019-09-30
lastday_month = a.ceil('month').date()
print(lastday_month)

# 获取unix时间戳,长度10位
ten_timestamp = a.timestamp
print(ten_timestamp)

# unix 时间戳转成对应时间 eg: 1535113845  to  2018-08-24 12:30:45
since_time = arrow.get(ten_timestamp)
# utc 时间 eg : 2019-09-23 15:22:04 差8小时
print(since_time.format("YYYY-MM-DD HH:mm:ss"))
# 转成本地时间 eg : 2019-09-23 23:22:04
print(since_time.to('local').format("YYYY-MM-DD HH:mm:ss"))
  • python常用的时间处理方法
import arrow,datetime
def get_date(num):
    """返回距离现在num天前的日期"""
    return (datetime.today() - timedelta(days = num)).strftime("%Y-%m-%d")

def to_date(thedate):
    return arrow.get(thedate,"YYYY-MM-DD")

def datediff(start,end):
    """计算时间差多少天"""
    start = to_date(start)
    end = to_date(end)
    return (end-start).days

def to_str(thedate):
    return str(thedate)[:10]

def get_date(num = 0,thedate = ''):
    """计算指定时间的前N天
    例如:
    get_date(1),返回昨天的日期
    get_date(0),返回今天的日期
    """
    if thedate == '':
        thedate = arrow.now().format('YYYY-MM-DD')
        return str(to_date(thedate).shift(days = -num))[:10]
    else:
        return str(to_date(thedate).shift(days=-num))[:10]

def get_day(thedate,num):
    """计算当前时间的后N天"""
    return str(to_date(thedate).shift(days=num))[:10]

def get_month(thedate,num):
    """计算当前时间N月后的今天"""
    return str(to_date(thedate).shift(months=num))[:10]

def get_month_first(thedate,num):
    """计算当前时间N月后的月第一天"""
    return str(to_date(thedate).shift(months=num))[:8]+'01'

def get_year(thedate,num):
    """计算当前时间N年后的今天"""
    return str(to_date(thedate).shift(years=num))[:10]

def get_year_first(thedate,num):
    """计算当前时间N年后的年第一天"""
    return str(to_date(thedate).shift(years=num))[:8]+'01'

def datediff(start,end):
    """计算时间差多少天"""
    start = to_date(start)
    end = to_date(end)
    return (end-start).days
posted @ 2021-05-07 23:50  介个车车烫屁股  阅读(117)  评论(0编辑  收藏  举报