Python你可能会用到的时间比较

简介:

    最近用Python来做时间的比较,整理一下。

    场景:数据库保存的是datetime.datetime.now()的str类型的数据,需要把数据库保存的时间跟现在的时间进行比较。

    用到的库:datetime.datetime.now()    datetime.datetime.strptime()    datetime.timedelta()

数据模拟:

1
2
3
4
5
6
7
8
9
10
11
>>>  from  datetime  import  datetime, timedelta
>>> nowtime  =  datetime.now()     # 现在的时间
>>> nowtime
datetime.datetime( 2017 6 20 20 11 12 926763 )
>>> 
>>> lasthour  =  datetime( 2017 6 20 19 11 12 926763 )     # 1个小时前的时间
>>> lasthour
datetime.datetime( 2017 6 20 19 11 12 926763 )
>>> lasthour_str  =  str (lasthour)           # 模拟从数据库取出来的str类型时间数据
>>> lasthour_str
'2017-06-20 19:11:12.926763'

str时间数据转换:

1
2
3
4
# 将str类型时间数据转换为datetime.datetime类型时间数据
>>> lasthour_new  =  datetime.strptime(lasthour_str,  '%Y-%m-%d %H:%M:%S.%f' )
>>> lasthour_new
datetime.datetime( 2017 6 20 19 11 12 926763 )

时间比较:

1
2
3
4
5
6
7
8
9
10
11
12
# lasthour_new和nowtime的时间差是否大于1个小时
>>> nowtime  -  lasthour_new > timedelta(hours = 1 )
False
# lasthour_new和nowtime的时间差是否等于1个小时
>>> nowtime  -  lasthour_new  = =  timedelta(hours = 1 )
True
# lasthour_new和nowtime的时间差是否大于60分钟
>>> nowtime  -  lasthour_new > timedelta(minutes = 60 )
False
# lasthour_new和nowtime的时间差是否等于60分钟
>>> nowtime  -  lasthour_new  = =  timedelta(minutes = 60 )
True




本文转自 xpleaf 51CTO博客,原文链接:http://blog.51cto.com/xpleaf/1940304,如需转载请自行联系原作者

相关文章
|
3月前
|
Python
我严重怀疑我会Python吗
我严重怀疑我会Python吗
13 0
|
Python Windows
Python 获取视频时长(附代码) | Python工具
Python 获取视频时长(附代码) | Python工具
Python 获取视频时长(附代码) | Python工具
|
4天前
|
Python
求助 当前python 3.12.3 怎么解决
在尝试从`modelscope.pipelines`导入`pipeline`时,遇到了导入错误。问题出在`modelscope.msdatasets.utils.hf_datasets_util`模块尝试从`datasets.utils`导入`_datasets_server`,但该名称未找到,可能应导入的是`_dataset_viewer`。这是Python项目中的一个依赖冲突或库更新问题。
|
1月前
|
缓存 调度 开发者
Python 时间处理
【2月更文挑战第6天】 Python 时间处理
35 1
|
2月前
|
数据采集 Web App开发 搜索推荐
十分钟带你搞懂Python那啥
十分钟带你搞懂Python那啥
17 0
|
2月前
|
SQL Java 编译器
使用pypy来提升你的python项目性能
使用pypy来提升你的python项目性能
47 0
|
9月前
|
Python
python里面时间相关处理总结
python里面时间相关处理总结
30 0
|
9月前
|
IDE 数据挖掘 Linux
为什么你的python版本一团糟?因为少了这个操作
在这里我要说明下,对于初学者来说,版本间的语法差异其实并不大。现在刚开始学 Python 的人,放心大胆地用最新版本即可。业内所诟病的,主要是针对代码上的不兼容。
【python】使用python将多个视频合并、延长视频的时间
今天做知识分享的时候,最后保存的视频时长是58分钟,那么如何改变视频的时长,将视频时长改为一个小时呢?请阅读下面的文章。
【python】使用python将多个视频合并、延长视频的时间
|
C++ Python Windows
比 Python 快得吓人,PyPy 极简入门
比 Python 快得吓人,PyPy 极简入门
比 Python 快得吓人,PyPy 极简入门