Python常用的日期和时间操作方法范例大全

2022-05-03 00:00:00 常用 范例 操作方法

下面的代码提供了python常用的日期使用方法,包括日期转换,获得当前时间,获得多少天以后的日期等等,非常全面。

"""
作者:皮蛋编程(https://www.pidancode.com)
创建日期:2022/3/25
功能描述:Python常用的日期和时间操作方法范例大全
"""

import datetime


# 给定日期向后N天的日期
def dateadd_day(days):
    d1 = datetime.datetime.now()
    d3 = d1 + datetime.timedelta(days)
    return d3


# 昨天
def getYesterday():
    today = datetime.date.today()
    oneday = datetime.timedelta(days=1)
    yesterday = today - oneday
    return yesterday


# 今天
def getToday():
    return datetime.date.today()


# 获取给定参数的前几天的日期,返回一个list
def getDaysBefore(num):
    today = datetime.date.today()
    oneday = datetime.timedelta(days=1)
    li = []
    for i in range(0, num):
        # 今天减一天,一天一天减
        today = today - oneday
        # 把日期转换成字符串
        li.append(datetostr(today))
    return li


# 将字符串转换成datetime类型
def strtodatetime(datestr, format):
    return datetime.datetime.strptime(datestr, format)


# 时间转换成字符串,格式为2015-02-02
def datetostr(date):
    return str(date)[0:10]


# 时间转换成字符串,格式为2015-02-02
def datetostr_secod(date):
    return str(date)[0:19]


# 两个日期相隔多少天,例:2015-2-04和2015-3-1
def datediff(beginDate, endDate):
    format = "%Y-%m-%d"
    bd = strtodatetime(beginDate, format)
    ed = strtodatetime(endDate, format)
    oneday = datetime.timedelta(days=1)
    count = 0
    while bd != ed:
        ed = ed - oneday
        count += 1
    return count


# 两个日期之间相差的秒
def datediff_seconds(beginDate, endDate):
    format = "%Y-%m-%d %H:%M:%S"
    if " " not in beginDate or ':' not in beginDate:
        bformat = "%Y-%m-%d"
    else:
        bformat = format
    if " " not in endDate or ':' not in endDate:
        eformat = "%Y-%m-%d"
    else:
        eformat = format
    starttime = strtodatetime(beginDate, bformat)
    endtime = strtodatetime(endDate, eformat)
    ret = endtime - starttime
    return ret.days * 86400 + ret.seconds


# 获取两个时间段的所有时间,返回list
def getDays(beginDate, endDate):
    format = "%Y-%m-%d"
    begin = strtodatetime(beginDate, format)
    oneday = datetime.timedelta(days=1)
    num = datediff(beginDate, endDate) + 1
    li = []
    for i in range(0, num):
        li.append(datetostr(begin))
        begin = begin + oneday
    return li


# 获取当前年份 是一个字符串
def getYear(date=datetime.date.today()):
    return str(date)[0:4]


# 获取当前月份 是一个字符串
def getMonth(date=datetime.date.today()):
    return str(date)[5:7]


# 获取当前天 是一个字符串
def getDay(date=datetime.date.today()):
    return str(date)[8:10]


# 获取当前小时 是一个字符串
def getHour(date=datetime.datetime.now()):
    return str(date)[11:13]


# 获取当前分钟 是一个字符串
def getMinute(date=datetime.datetime.now()):
    return str(date)[14:16]


# 获取当前秒 是一个字符串
def getSecond(date=datetime.datetime.now()):
    return str(date)[17:19]


def getNow():
    return datetime.datetime.now()


print(dateadd_day(10))
# 2022-04-04 08:26:09.554107
print(getYesterday())
# 2022-03-24
print(getToday())
# 2022-03-25
print(getDaysBefore(3))
# ['2022-03-24', '2022-03-23', '2022-03-22']
print(datediff('2015-2-01', '2015-10-05'))
# 246
print(datediff_seconds('2015-02-04', '2015-02-05'))
# 86400
print(datediff_seconds('2015-02-04 22:00:00', '2015-02-05'))
# 7200
print(getDays('2015-2-03', '2015-2-05'))
# ['2015-02-03', '2015-02-04', '2015-02-05']
print(datetostr_secod(getNow()))
# 2022-03-25 08:26:09
print(str(getYear(dateadd_day(-50))) + '-' \
      + getMonth() + '-' \
      + getDay() + ' ' \
      + getHour() + ':' \
      + getMinute() + ':' \
      + getSecond())
# 2022-03-25 08:26:09
print(getNow())
# 2022-03-25 08:26:09.556344

以上代码在python3.9环境下测试通过。

相关文章