python time datetime模块最详尽讲解

Posted bitcarmanlee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python time datetime模块最详尽讲解相关的知识,希望对你有一定的参考价值。

0.前言

python中常用的时间模块包括time与datetime。之前虽然一直在用相关模块,但是没有做过系统总结,理解也不是很到位,没有做到融会贯通的程度。正好趁着项目中正在写相关代码,顺便做个总结,争取所有人看到此文对这两个模块都有很清晰的认知。

1.time模块

要想了解一个模块的大致情况,首先我们可以点到相关源码中看看注释说明。

"""
This module provides various functions to manipulate time values.

There are two standard representations of time.  One is the number
of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer
or a floating point number (to represent fractions of seconds).
The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
The actual value can be retrieved by calling gmtime(0).

The other representation is a tuple of 9 integers giving local time.
The tuple items are:
  year (including century, e.g. 1998)
  month (1-12)
  day (1-31)
  hours (0-23)
  minutes (0-59)
  seconds (0-59)
  weekday (0-6, Monday is 0)
  Julian day (day in the year, 1-366)
  DST (Daylight Savings Time) flag (-1, 0 or 1)
If the DST flag is 0, the time is given in the regular time zone;
if it is 1, the time is given in the DST time zone;
if it is -1, mktime() should guess based on the date and time.
"""

上面的注释给出了两个最重要的信息:
在time模块中,有两种表示时间的方式,一种是时间戳,一种是包含9个整数的元组,即后面提到的struct_time。

在python相关文档中,time跟操作系统联系比较紧密,是属于操作系统比较底层的操作。

2.时间戳与日期相互转换

实际中最常见的需求就是时间戳与日期之间的相互转换,我们来看看在python中怎么操作。

def timestamp2date():
    import time

    # timestamp -> struct_time -> str
    timestamp = 1462451334
    time_local = time.localtime(timestamp)
    date = time.strftime("%Y%m%d", time_local)

    print("date is: ", date)

时间戳转日期,核心是localtime方法,该方法是把时间戳转化为struct_time结构,然后再通过strftime方法变成自己想要的格式。

如果我们查看一下localtime的源码

def localtime(seconds=None): # real signature unknown; restored from __doc__
    """
    localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
                              tm_sec,tm_wday,tm_yday,tm_isdst)
    
    Convert seconds since the Epoch to a time tuple expressing local time.
    When 'seconds' is not passed in, convert the current time instead.
    """
    pass

里面就有strcut_time的结构描述,即上面提到的包含九个整数的元组:
年,月,日,小时,分钟,秒,星期几,一年中的第几天,是否为夏令时

如果反过来想把日期转化为时间戳

def date2timestamp():
    import time

    # str -> struct_time -> timestamp
    date = "20160505"
    struct_time = time.strptime(date, "%Y%m%d")
    timestamp = time.mktime(struct_time)

    print("timestamp is: ", timestamp)

基本思路还是通过struct_time这个结构,先把字符串用strptime方法变成struct_time,在用mktime方法得到时间戳。

3.格式化时间

格式化时间也是我们常用的功能。下面看个例子

def formatdate():
    import time
    date = "20160505"
    struct_date = time.strptime(date, "%Y%m%d")
    new_date = time.strftime("%Y-%m-%d", struct_date)
    print("new date is: ", new_date)

上述例子中给定的日期原格式是yyyymmdd,想要变成yyyy-mm-dd的格式,分别公国strptime与strftime两次转化即可。

4.time模块中其他常用的几个方法

def time_method():
    import time
    # 当前时间戳
    print(time.time())
    
    # Delay execution for a given number of seconds.  The argument may be
    a floating point number for subsecond precision.
    print(time.sleep(2))
    
    # Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
    When the time tuple is not present, current time as returned by localtime()
    is used.
    print(time.asctime())

上述代码运行结果

1639916424.829865
None
Sun Dec 19 20:20:26 2021

5.datetime模块

从前面讲解time模块的部分不难看出来,time模块比较底层,能完成的功能相对有限,这个时候就需要更高级的datetime模块来参与了,甚至我们可以简单理解为,datetime模块是对time模块进行了更高一层的封装。

datetime模块中主要的类包括
datetime:包括时间与日期
timedelta:包括时间间隔
tzinfo:包括时区
date:包括日期
time:包括时间

实际中,使用最多的是datetime与timedelta两个类,其他的相对较少。

我们查看一下datetime类的源码

class datetime(date):
    """datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])

    The year, month and day arguments are required. tzinfo may be None, or an
    instance of a tzinfo subclass. The remaining arguments may be ints.
    """
    __slots__ = date.__slots__ + time.__slots__

    def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
                microsecond=0, tzinfo=None, *, fold=0):
...

不难看出,datetime中包含了年,月,日,小时,分钟,秒,毫秒,时区等信息。

而deltatime源码如下

class timedelta:
    """Represent the difference between two datetime objects.

    Supported operators:

    - add, subtract timedelta
    - unary plus, minus, abs
    - compare to timedelta
    - multiply, divide by int

    In addition, datetime supports subtraction of two datetime objects
    returning a timedelta, and addition or subtraction of a datetime
    and a timedelta giving a datetime.

    Representation: (days, seconds, microseconds).  Why?  Because I
    felt like it.
    """
    __slots__ = '_days', '_seconds', '_microseconds', '_hashcode'

    def __new__(cls, days=0, seconds=0, microseconds=0,
                milliseconds=0, minutes=0, hours=0, weeks=0):
...

第一句就点明了timedelta的用途:

Represent the difference between two datetime objects.
在两个datetime对象之间表示时间差。

def time_delta():
    from datetime import datetime, timedelta

    # now()方法返回一个datetime.datetime对象
    # "Construct a datetime from time.time() and optional time zone info."
    now = datetime.now()
    nowdate = datetime.strftime(now, "%Y%m%d")
    print("nowdate is: ", nowdate)

    # 求未来几天
    nextday = now + timedelta(days=1)
    nextdate = datetime.strftime(nextday, "%Y%m%d")
    print("nextdate is: ", nextdate)

    # 求相差几天
    span = nextday - now
    print("span is: ", span)
    print("span.days is: ", span.days)
    print("span.seconds is: ", span.total_seconds())

    # 获取一段时间
    daylist = []
    for i in range(10):
        curday = now + timedelta(days=i)
        curdate = datetime.strftime(curday, "%Y%m%d")
        daylist.append(curdate)

    print("daylist is: ", daylist)


time_delta()

上面代码输出:

nowdate is:  20211219
nextdate is:  20211220
span is:  1 day, 0:00:00
span.days is:  1
span.seconds is:  86400.0
daylist is:  ['20211219', '20211220', '20211221', '20211222', '20211223', '20211224', '20211225', '20211226', '20211227', '20211228']

Process finished with exit code 0

上面的代码解决了我们常用的几个功能:
1.求未来/之前几天时间。
2.求两天之间时间差。
3.生成一段连续时间。

6.总结

所以最后总结下来,在python中与时间相关的用途,其实就这么几点:
1.与时间戳相关的转化,可以在time模块中,通过struct_time这个结构作为中间对象,进行各种转化。
2.与时间格式相关的转化,也可以在time模块中,运用strptime与strftime两个模块,借助struct_time这个结构进行转化。
3.与时间差相关的,可以综合使用datetime模块中的datetime与timedelta两个对象计算达到目的。

以上是关于python time datetime模块最详尽讲解的主要内容,如果未能解决你的问题,请参考以下文章

time模块 | datetime模块 | Python

#15 time&datetime&calendar模块

python的time&datetime模块

python常用模块之time&datetime模块

Python time和datetime模块

python datetime模块