Python 日期 的 加减 等 操作

 

datetime — Basic date and time types:https://docs.python.org/3.8/library/datetime.html

dateutil --- powerful extensions to datetime:https://dateutil.readthedocs.io/en/stable/index.html

Python time 和 datetime 的常用转换处理:https://www.cnblogs.com/lxmhhy/p/6030730.html

 

  • datetime 转 timestamp
  • datetime 转 时间字符串
  • timestamp 转 datetime
  • timestamp 转 时间字符串
  • 时间字符串 转 datetime
  • 时间字符串 转 timestamp

对于这三者的转换,python2和python3是不同的,因为在python3中新增一些实例方法,能够很方便的实现这些类型之间的转换。

如果需要python2的类型转换请移步这些文章:
python --- 时间与时间戳之间的转换:https://blog.csdn.net/google19890102/article/details/51355282
Python 字符串、时间戳、datetime 时间相关转换:https://blog.csdn.net/Data_Ada/article/details/72900019

简单介绍下,datetime 和 time 中常用的方法

  • datetime.datetime.strptime(string, format)。类方法,作用是根据指定的format(格式),将字符串转换成datetime.datetime实例对象。
  • datetime.datetime.strftime(format): 实例方法,作用就是根据指定的format(格式),将datetime.datetime实例对象转换成时间字符串。
  • datetime.datetime.timestamp(): 实例方法,作用就是将datetime.datetime实例对象转换成时间戳。
  • datetime.fromtimestamp(timestamp, tz=None):类方法,作用是将时间戳转换成datetime.datetime对象。
  • time.strptime(string, format)。类方法,作用是根据指定的format(格式)将时间字符串转换成time.struct_time对象。
  • time.strftime(format, string)。类方法,作用是根据指定的format(格式,)将time.struct_time对象转换成时间字符串。
  • time.localtime(timestamp)。类方法,作用是将时间戳转换成本地时间的time.struct_time对象。若要转换成UTC的time.struct_time对象则使用time.gtime()。
  • time.mktime(t)。类方法,time.localtime()的逆函数,因为作用正好相反。其作用是将time.struct_time对象转换成时间戳。

 

示例:

# 把 datetime 转成 字符串
def datetime_toString(dt):return dt.strftime("%Y-%m-%d-%H")# 把 字符串 转成 datetime
def string_toDatetime(string):return datetime.strptime(string, "%Y-%m-%d-%H")# 把 字符串 转成 时间戳形式
def string_toTimestamp(strTime):return time.mktime(string_toDatetime(strTime).timetuple())# 把 时间戳 转成 字符串形式
def timestamp_toString(stamp):return time.strftime("%Y-%m-%d-%H", tiem.localtime(stamp))# 把 datetime类型 转成 时间戳形式
def datetime_toTimestamp(dateTim):return time.mktime(dateTim.timetuple())

 

 

datetime timestamp

 

直接使用 datetime 模块中 datetime类 的 timestamp() 实例方法。

import datetime
import timedt = datetime.datetime.now()
ts = dt.timestamp()
print(f'{type(dt)} : {dt}')  
print(ts)               

 

 

datetime 时间字符串

 

直接使用 datetime 模块中的 datetime类 的 strftime() 实例方法即可。

import datetime
import timedt = datetime.datetime.now()# 根据此格式来解析datetime.datetime()对象为时间字符串
format_string = '%Y-%m-%d %H:%M:%S'print(f'{type(dt)} : {dt}')
print(dt.strftime(format_string))

 

 

timestamp datetime

 

import datetime
import timets = 1568172006.68132  # 时间戳
dt = datetime.datetime.fromtimestamp(ts)
print(dt)

 

 

timestamp 时间字符串

 

  1. 如果使用 time 模块,转换必须通过 time.struct_time对象作为桥梁。

  2. 如果使用 datetime 模块,先转成 datetime.datetime 对象,再转成时间字符串。

示例代码:

import datetime
import time# 方法 1
ts = 1568172006.68132                # 时间戳
format_string = '%Y-%m-%d %H:%M:%S'  # 根据此格式来时间戳解析为时间字符串
# 时间戳转time.struct_time
ts_struct = time.localtime(ts)
# time.struct_time 转时间字符串
date_string = time.strftime(format_string, ts_struct)print(date_string)  # '2019-09-11 11:20:06'# 方法 2
dt = datetime.datetime.fromtimestamp(ts)
date_string = dt.strftime(format_string)

 

 

时间字符串datetime

 

只需要使用 datetime模块 中的 datetime类 的 strptime(date_string, format)类方法即可。
这个方法的作用就是:根据指定的 format 格式将时间字符串 date_string,转换成 datetime.datetime()对象。

import datetime
import timedate_string = '2019-09-11 11:20:06'
# 根据此格式来解析时间字符串为datetime.datetime()对象
format_string = '%Y-%m-%d %H:%M:%S'dt = datetime.datetime.strptime(date_string, format_string)
print(dt)  # datetime.datetime(2019, 9, 11, 11, 20, 6)

 

 

时间字符串timestamp

 

  1. 方法 1:如果使用 time 模块,转换必须通过 time.struct_time 对象作为桥梁。

  2. 方法 2:如果使用 datetime 模块,先转成 datetime.datetime 对象,再转成 timestamp。

示例代码:

import datetime
import time# 方法 1
date_string = '2019-09-11 11:20:06'
format_string = '%Y-%m-%d %H:%M:%S'  # 根据此格式来解析时间字符串为time()对象# 时间字符串转 time.struct_time
ts_struct = time.strptime(date_string, format_string)
# time.struct_time 转时间戳
ts = time.mktime(ts_struct)
print(ts)  # 1568172006.0# 方法 2
dt = datetime.datetime.strptime(date_string, format_string)
ts = dt.timestamp()

 

 

日期输出格式化

 

所有日期、时间的 api 都在 datetime 模块内。

1. datetime  ----->  string

import datetimeif __name__ == '__main__':now = datetime.datetime.now()t = now.strftime('%Y-%m-%d %H:%M:%S')print(type(t), t)# 结果:<class 'str'> 2019-12-13 14:08:35

strftime 是 datetime类 的实例方法。

 

import time

time.strftime

"""
strftime(format[, tuple]) -> stringConvert a time tuple to a string according to a format specification.
See the library reference manual for formatting codes. When the time tuple
is not present, current time as returned by localtime() is used.Commonly used format codes:%Y  Year with century as a decimal number.
%m  Month as a decimal number [01,12].
%d  Day of the month as a decimal number [01,31].
%H  Hour (24-hour clock) as a decimal number [00,23].
%M  Minute as a decimal number [00,59].
%S  Second as a decimal number [00,61].
%z  Time zone offset from UTC.
%a  Locale's abbreviated weekday name.
%A  Locale's full weekday name.
%b  Locale's abbreviated month name.
%B  Locale's full month name.
%c  Locale's appropriate date and time representation.
%I  Hour (12-hour clock) as a decimal number [01,12].
%p  Locale's equivalent of either AM or PM.Other codes may be available on your platform.  See documentation for
the C library strftime function.
"""

time.strptime

"""
strptime(string, format) -> struct_timeParse a string to a time tuple according to a format specification.
See the library reference manual for formatting codes (same as
strftime()).Commonly used format codes:%Y  Year with century as a decimal number.
%m  Month as a decimal number [01,12].
%d  Day of the month as a decimal number [01,31].
%H  Hour (24-hour clock) as a decimal number [00,23].
%M  Minute as a decimal number [00,59].
%S  Second as a decimal number [00,61].
%z  Time zone offset from UTC.
%a  Locale's abbreviated weekday name.
%A  Locale's full weekday name.
%b  Locale's abbreviated month name.
%B  Locale's full month name.
%c  Locale's appropriate date and time representation.
%I  Hour (12-hour clock) as a decimal number [01,12].
%p  Locale's equivalent of either AM or PM.Other codes may be available on your platform.  See documentation for
the C library strftime function.
"""

更多 time() 模块函数,可以查看 time() 模块

 

2. string  ----->  datetime

import datetimeif __name__ == '__main__':t_str = '2012-03-05 16:26:23'd = datetime.datetime.strptime(t_str, '%Y-%m-%d %H:%M:%S')print(type(d), d)# 结果:<class 'datetime.datetime'> 2012-03-05 16:26:23

strptime 是 datetime类 的 静态方法。

 

 

日期比较操作

 

在 datetime 模块中有 timedelta类,这个类的对象用于表示一个时间间隔,比如两个日期或者时间的差别。

构造方法:

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

所有的参数都有默认值0,这些参数可以是int或float,正的或负的。

可以通过 timedelta.days、tiemdelta.seconds 等获取相应的时间值。

timedelta类的实例支持加、减、乘、除等操作,所得的结果也是 timedelta类 的 实例。比如:

year = timedelta(days=365)
ten_years = year *10
nine_years = ten_years - year

同时,date、time 和 datetime 类也支持与 timedelta 的加、减运算。

datetime1 = datetime2 +/- timedelta
timedelta = datetime1 - datetime2

这样,可以很方便的实现一些功能。

1. 两个日期相差多少天。

import datetimeif __name__ == '__main__':d1 = datetime.datetime.strptime('2012-03-05 17:41:20', '%Y-%m-%d %H:%M:%S')d2 = datetime.datetime.strptime('2012-03-02 17:41:20', '%Y-%m-%d %H:%M:%S')delta = d1 - d2        print(type(delta), delta.days)# 结果:<class 'datetime.timedelta'> 3

2. 今天的 n 天后的日期。

import datetimeif __name__ == '__main__':now = datetime.datetime.now()delta = datetime.timedelta(days=3)n_days = now + deltaprint(n_days.strftime('%Y-%m-%d %H:%M:%S'))# 结果:2019-12-16 14:14:06

示例代码:

import datetimenow = datetime.datetime.now()
print(now)# 将日期转化为字符串 datetime => string
print(now.strftime('%Y-%m-%d %H:%M:%S'))t_str = '2012-03-05 16:26:23'
# 将字符串转换为日期 string => datetime
d = datetime.datetime.strptime(t_str, '%Y-%m-%d %H:%M:%S')
print(d)# 在datetime模块中有timedelta类,这个类的对象用于表示一个时间间隔,比如两个日#期或者时间的差别。# 计算两个日期的间隔
d1 = datetime.datetime.strptime('2012-03-05 17:41:20', '%Y-%m-%d %H:%M:%S')
d2 = datetime.datetime.strptime('2012-03-02 17:41:20', '%Y-%m-%d %H:%M:%S')
delta = d1 - d2
print(delta.days)
print(delta)# 今天的n天后的日期。
now = datetime.datetime.now()
delta = datetime.timedelta(days=3)
n_days = now + delta
print(n_days.strftime('%Y-%m-%d %H:%M:%S'))# 结果
# 2019-12-13 14:23:35.819567
# 2019-12-13 14:23:35
# 2012-03-05 16:26:23
# 3
# 3 days, 0:00:00
# 2019-12-16 14:23:35

示例代码 :

import time
import datetimeif __name__ == '__main__':now_time = datetime.datetime.now()  # 当前时间now_time_mk = time.mktime(now_time.timetuple())  # 当前时间戳current_month = now_time.month# 下月第一天最后一秒时间if current_month == 12:        next_mouth_first_day = datetime.datetime(now_time.year + 1, 1, 1, 23, 59, 59)else:next_mouth_first_day = datetime.datetime(now_time.year, current_month + 1, 1, 23, 59, 59)# 当前月最后一天current_month_last_day = next_mouth_first_day - datetime.timedelta(days=1)# 当前月第一天current_month_first_day = datetime.date(now_time.year, now_time.month, 1)# 前一月最后一天pre_month_last_day = current_month_first_day - datetime.timedelta(days=1)# 前一月第一天pre_month_first_day = datetime.date(pre_month_last_day.year, pre_month_last_day.month, 1)print(next_mouth_first_day)print(current_month_last_day)print(current_month_first_day)print(pre_month_last_day)print(pre_month_first_day)'''
结果:
2020-01-01 23:59:59
2019-12-31 23:59:59
2019-12-01
2019-11-30
2019-11-01
'''

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/496019.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

计算机网络技术专业的规划,计算机网络技术专业建设规划

附件2:计算机网络技术专业建设规划专业建设与发展是高职教育人才培养的重要依据&#xff0c;决定着人才培养质量和培养规格&#xff0c;体现了学校的办学实力与办学水平。2012年以前&#xff0c;电子信息工程系有三个专业&#xff0c;分别是计算机应用技术专业、电子商务专业&a…

SpringBoot 自带工具类~FileCopyUtils

org.springframework.util.FileCopyUtils 1、输入 // 从文件中读入到字节数组中 byte[] copyToByteArray(File in) // 从输入流中读入到字节数组中 byte[] copyToByteArray(InputStream in) // 从输入流中读入到字符串中 String copyToString(Reader in) 2、输出 /…

ReaderMe 1.0.0.32版发布

2010-03-09 ReaderMe 1.0.0.321、添加“Ctrl M”快捷键&#xff0c;在当前光标位置做书签。2、更新软件内的主页链接&#xff0c;由原来的谷歌站点&#xff0c;改为博客园。 点击下载最新版本 转载于:https://www.cnblogs.com/gaoyunpeng/archive/2010/03/09/1681571.html

乐山市计算机学校太坑,乐山市计算机学校小规矩成就大素养

没有规矩&#xff0c;不成方圆。规矩&#xff0c;虽然约束了我们的一些行为&#xff0c;但究其根本是保障了大家的基本利益&#xff0c;使我们的学习、生活、工作有序推进。在乐山市计算机学校&#xff0c;我们有校规校纪&#xff0c;“十条红线”、“三不两禁”的学生管理办法…

牛津大学计算机系主任:人工智能立法重在抓机遇、防危害

来源&#xff1a;科技日报 作者&#xff1a;郑焕斌“人工智能立法的重点应在于充分利用AI技术所提供的各种机遇&#xff0c;构建适宜的环境以激励、培育大量AI初创公司和新服务的发展&#xff0c;防范和应对AI技术所带来的各种潜在危害。”牛津大学计算机系主任迈克尔伍尔德里…

Python 数据可视化:WordCloud 词云的构建

WordCloud 官方文档&#xff1a;https://amueller.github.io/word_cloud/index.html WordCloud GitHub 地址&#xff1a;https://github.com/amueller/word_cloud Python非常重要的一个可视化库&#xff0c;wordcloud词云库了解一下&#xff01;&#xff1a;https://www.bilibi…

关于deepearth的一点小问题

我下载的deepEarth的源代码&#xff0c;编译以后有错误&#xff0c;不知怎么办&#xff0c;不知道各位用没用过deepEarth啊&#xff1f;请高手指教&#xff01; 转载于:https://www.cnblogs.com/kakaleilei/archive/2010/03/09/1681608.html

SpringBoot 自带工具类~ResourceUtils

org.springframework.util.ResourceUtils 1、从资源路径获取文件 // 判断字符串是否是一个合法的 URL 字符串。 static boolean isUrl(String resourceLocation) // 获取 URL static URL getURL(String resourceLocation) // 获取文件&#xff08;在 JAR 包内无法正常…

计算机术语局部性,【计算机基础】程序的局部性简介

什么是局部性&#xff1f;局部性分类局部性有什么作用&#xff1f;局部性举例数据引用的局部性取指令的局部性结论完整代码什么是局部性&#xff1f;程序倾向于使用它们最近使用的地址接近或相等的数据和指令。局部性分类局部性主要分为时间局部性和空间局部性。时间局部性&…

卫星还在“织网” 北斗时代尚需时日

来源&#xff1a;科技日报 作者&#xff1a;付丽丽生活在大都市里的人们&#xff0c;出门如果没有手机导航&#xff0c;会感觉自己像盲人一样不会走路。而让人更无法忍受的&#xff0c;则是傻导航的瞎导乱导&#xff0c;“我就老跟导航吵架&#xff0c;气得我把手机摔了的心都…

Python3.5 queue 模块详解 和 进程间通讯

queue — A synchronized queue class&#xff1a;https://docs.python.org/3/library/queue.html 菜鸟教程 - Python3 多线程&#xff1a;http://www.runoob.com/python3/python3-multithreading.html python3 队列&#xff1a;https://cloud.tencent.com/developer/informa…

领域模型中的各种角色

实体 实体是具有唯一标识的对象,且该标识和对象的属性值分离.即使两个实体的属性完全相同,这两个实体也相同,不能交换使用.由于实体通常对应于现实世界的概念. 是领域模型的中心,因此实体的标识非常重要. 值对象 值对象是主要由其属性值定义的对象.值对象通常不可变,即一旦创建…

5大洲,32个国家:剑桥分析公司的触角到底有多远?

来源&#xff1a; 资本实验室 作者&#xff1a;王进据Facebook最新披露的信息&#xff0c;剑桥分析公司&#xff08;Cambridge Analytica&#xff09;经由Facebook平台泄露数据影响的用户数量从5000万增加到8700万。其中&#xff0c;美国占比81.6&#xff05;&#xff0c;也就…

计算机房的分类,雅思词汇分类积累之计算机房

雅思词汇在雅思考试中占据着很重要的位置&#xff0c;是各部分考试的基础&#xff0c;今天新东方在线小编给大家整理了雅思词汇分类积累之计算机房&#xff0c;希望能够帮助大家顺利的通过考试&#xff0c;一起来看看吧!硬件mainframe主机,monitor监视器&#xff0c;显示器,scr…

CSRF攻击与防御(写得非常好)

From&#xff1a;https://www.daguanren.cc/post/csrf-introduction.html From&#xff1a;https://blog.csdn.net/stpeace/article/details/53512283 CSRF 攻击的应对之道&#xff1a;https://www.ibm.com/developerworks/cn/web/1102_niugang_csrf WEB三大攻击之—CSRF攻击与…

使用AvalonDock制作WPF多标签浏览器(一)

AvalonDock是CodePlex上的一个开源项目&#xff0c;利用它可以很容易的做出类似于VS的UI效果。下图是AvalonDock源码中自带的一个Demo&#xff1a;我们可以用这款第三方控件为基础来制作多标签浏览器。下面是最终效果图&#xff1a;甚至可以把其中一个标签拖出主窗体成为一个独…

SpringBoot 自带工具类~StreamUtils

org.springframework.util.StreamUtils 1、输入 void copy(byte[] in, OutputStream out) int copy(InputStream in, OutputStream out) void copy(String in, Charset charset, OutputStream out) long copyRange(InputStream in, OutputStream out, long start, long en…

量子计算机不会“秒杀”经典计算机

来源&#xff1a;《中国科学报》 作者&#xff1a;陈昭昀许多人在介绍量子计算机的时候&#xff0c;都喜欢用到“秒杀”这个词。比如&#xff1a;量子计算机将“秒杀”现有密码体系、量子计算机将“秒杀”经典计算机&#xff0c;甚至将量子计算机比作无所不能的“千手观音”&a…

计算机的定点运算器原理,计算机组成原理定点运算器的组成及结构.doc

计算机组成原理 第八章定点运算器的组成和结构1. 算术逻辑单元(简称ALU)? 针对每一种算术运算&#xff0c;都必须有一个相对应的基本硬件配置&#xff0c;其核心部件是加法器和寄存器。当需完成逻辑运算时&#xff0c;势必需要配置相应的逻辑电路&#xff0c; 而ALU电路是既能…

WEB三大攻击之—SQL注入攻击与防护

From&#xff1a;https://www.daguanren.cc/post/sql-injection.html SQL注入的定义与诱因 定义 SQL攻击&#xff08;英语&#xff1a;SQL injection&#xff09;&#xff0c;简称注入攻击&#xff0c;是发生于应用程序之数据库层的安全漏洞。简而言之&#xff0c;是在输入的…