python日期函数大全

  • Post category:Python

Python日期函数是处理日期和时间相关的函数库,它提供了各种处理日期和时间的方法,包括日期格式化、日期计算、日期比较等。在Python中,日期相关的函数库主要是datetime模块和time模块。

datetime模块

datetime模块提供了一个datetime类,该类包含了日期和时间的信息。其常用的函数有:

  1. datetime.date(year, month, day):返回一个表示日期的对象。

    python
    import datetime
    d = datetime.date(2021, 11, 1)
    print(d) # 2021-11-01

  2. datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]):返回一个表示日期和时间的对象。

    python
    import datetime
    dt = datetime.datetime(2021, 11, 1, 10, 30, 50)
    print(dt) # 2021-11-01 10:30:50

  3. datetime.datetime.now([tz]):返回当前日期和时间。

    python
    import datetime
    dt = datetime.datetime.now()
    print(dt) # 当前时间

  4. datetime.datetime.strptime(date_string, format):将字符串格式的日期时间转换为datetime对象。

    python
    import datetime
    date_str = '2021-11-01 10:30:50'
    dt = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
    print(dt) # 2021-11-01 10:30:50

  5. datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]):表示时间间隔,可用于日期和时间计算。

    python
    import datetime
    d1 = datetime.datetime(2021, 11, 1, 10, 30, 50)
    d2 = datetime.datetime(2021, 11, 1, 12, 30, 50)
    delta = d2 - d1
    print(delta) # 2:00:00

time模块

time模块提供了一些计算时间的函数,它的常用函数有:

  1. time.time():返回当前时间的时间戳(1970年1月1日零时零分零秒到现在的秒数)。

    python
    import time
    t = time.time()
    print(t) # 当前时间的时间戳

  2. time.localtime([secs]):将一个时间戳转换为本地时间的struct_time对象。如果没有参数,则返回当前时间的struct_time对象。

    python
    import time
    t = time.time()
    lt = time.localtime(t)
    print(lt) # 当前本地时间

  3. time.strftime(format[, t]):将struct_time对象格式化为字符串。

    python
    import time
    lt = time.localtime()
    str_time = time.strftime('%Y-%m-%d %H:%M:%S', lt)
    print(str_time) # 当前本地时间的字符串格式

以上是Python日期函数大全的部分内容,还有很多函数没有一一列举。希望可以帮助大家更加灵活地处理日期和时间。