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 -> strtimestamp = 1462451334time_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 -> timestampdate = "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 timedate = "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 bea 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 aninstance 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 intIn addition, datetime supports subtraction of two datetime objectsreturning a timedelta, and addition or subtraction of a datetimeand a timedelta giving a datetime.Representation: (days, seconds, microseconds).  Why?  Because Ifelt 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 - nowprint("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模块最详尽讲解相关推荐

  1. python中datetime模块常用方法_Python中datetime的使用和常用时间处理

    datetime在python中比较常用,主要用来处理时间日期,使用前先倒入datetime模块.下面总结下本人想到的几个常用功能. 1.当前时间: >>> print dateti ...

  2. python的datetime模块需要装吗,Python datetime模块的介绍(日期格式化 时间戳)

    datetime模块常用的主要有下面这四个类:(要清楚import datetime : 导入的是datetime这个包,包里有各种类) 1. datetime.date   用于表示年月日构成的日期 ...

  3. python中datetime模块_python中的datetime模块

    datetime是python中日期和时间管理模块,包含date,time,datetime,timedelta,datetime_CAPI,sys,timezone等类 datetime模块中包含的 ...

  4. python之datetime模块

    目录 time模块和datetime模块的关系 time模块 datetime模块 日期和时间数据类型 数据类型 datetime参数 字符串转换 格式说明 dateutil NaT 时间序列基础 日 ...

  5. python的datetime模块用法_Python3.5内置模块之time与datetime模块用法实例分析

    本文实例讲述了python3.5内置模块之time与datetime模块用法.分享给大家供大家参考,具体如下: 1.模块的分类 a.标准库(python自带):sys.os模块 b.开源模块(第三方模 ...

  6. python利用datetime模块计算时间差

    python中通过datetime模块可以很方便的计算两个时间的差,datetime的时间差单位可以是天.小时.秒,甚至是微秒,下面我们就来详细看下datetime的强大功能吧 今天写了点东西,要计算 ...

  7. python 的datetime模块使用

    1.datetime模块主要是5个类 date #日期类 年月日 datetime.date(year,month,day) time #时间类 时分秒 datetime.time(hour,minu ...

  8. 【python】datetime模块计算时间差

    一.问题背景 最近有小伙伴反馈接口平台的测试计划执行耗时显示有误,比如执行实际时长超过10s,但是报告中显示总耗时小于1s 显示耗时统计出现问题 二.问题排查 开始和结束时间是否有误 开始时间: 20 ...

  9. python中datetime模块是以什么时间为基础_Python基础之datetime模块

    Outline 构建时间对象实例 date实例的构造 time实例的构造 datetime实例的构造 timedelta对象的构造 tzinfo介绍 时间转换 时间对象转字符串 字符串转时间对象 时间 ...

  10. python的datetime模块

    基础知识见: datetime 注意timestamp是一个浮点数,它没有时区的概念,而datetime是有时区的. timestamp的值与时区毫无关系,因为timestamp一旦确定,其UTC时间 ...

最新文章

  1. hanlp java_HanLP-实词分词器详解
  2. 华为机试第九题python
  3. PHP面试题:请以空格作为间隔,拆分字符串’Apple Orange Banana Strawberry’,组成数组$fruit,
  4. PWA(Progressive Web App)入门系列:Push
  5. Hive之架构 功能
  6. Android Studio 3.2升级后的编译问题解决办法
  7. 社区团购到底有什么魔力
  8. J2EE的核心API与组件
  9. 大数据质量管理策略有哪些
  10. 加速爬虫:异步加载asyncio
  11. 3. Longest Substring Without Repeating Characters
  12. C# List最大值最小值问题 List排序问题 List Max/Min
  13. Windows下保存git账号密码实现免输入
  14. python 每天定时运行程序(傻瓜式倒计时)
  15. 访问服务器本地端口/网址
  16. 扑克牌练习 【数据结构】
  17. Learning to Write Stylized Chinese Charactersby Reading a Handful of Examples
  18. 如何搭建一个自己的FTP服务器
  19. kafka 0.10.0 producer java代码实现
  20. 计算机常用英语单词1500

热门文章

  1. Java经典设计模式(3):十一种行为型模式(附实例和详解)
  2. Confluence 6 恢复一个空间
  3. Google Home其实是个错误
  4. java 通过网络 ntp 获取网络时间
  5. [leetcode]Two Sum @ Python
  6. 驱动lx4f120h,头文件配置,没有完全吃透,望指点
  7. 智能电视也需“杀毒”
  8. 用 maven 命令启动项目和直接用tomcat 启动项目的区别
  9. MATLAB获取字符串中两个特定字符之间的内容
  10. Tomcat监控利器Probe